当前位置:网站首页>30. 串联所有单词的子串
30. 串联所有单词的子串
2022-06-26 19:47:00 【北_尘】
今天看了下leetcode的第30题,题目链接:30. 串联所有单词的子串
题目如下:
给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符 ,但不需要考虑 words 中单词串联的顺序。
我这里使用了滑动切割字符串的方式,理解起来相对简单,代码如下;
public static List<Integer> findSubstring(String s, String[] words) {
int sLen = s.length();
int len = words.length;
int length = words[0].length();
Map<String,Integer> map = new HashMap();
List<Integer> list = new ArrayList<>();
//记录words得个数
for(String word : words){
map.put(word,map.getOrDefault(word,0)+1);
}
for (int i = 0; i <= sLen -len*length; i++) {
// 减少比较次数
if(map.containsKey(s.substring(i,i+length))
&& map.containsKey(s.substring(i+(len-1)*length,i+len*length))){
int index = i;
String tmp = "";
Map<String,Integer> tmpMap = new HashMap();
tmpMap.putAll(map);
while(index <= i+(len-1)*length){
tmp = s.substring(index,index+length);
if(tmpMap.containsKey(tmp)){
tmpMap.put(tmp,tmpMap.get(tmp)-1);
if(tmpMap.get(tmp) == 0){
tmpMap.remove(tmp);
}
}else{
break;
}
if(tmpMap.size() == 0){
list.add(i);
}
index += length;
}
}
}
return list;
}
边栏推荐
- 威胁猎人必备的六个威胁追踪工具
- Development of NFT for digital collection platform
- Case description: the competition score management system needs to count the competition scores obtained by previous champions and record them in the file. The system has the following requirements: -
- stm32和电机开发(直流有刷电机和步进电机)
- Unity——Mathf. Similarities and differences between atan and atan2
- 两个文件 合并为第三个文件 。
- Super VRT
- 【推荐收藏】这8个常用缺失值填充技巧一定要掌握
- Solidity - 合约继承子合约包含构造函数时报错 及 一个合约调用另一合约view函数收取gas费用
- 项目实战五:搭建ELk日志收集系统
猜你喜欢

Solidity - 合约继承子合约包含构造函数时报错 及 一个合约调用另一合约view函数收取gas费用

Tiktok practice ~ sharing module ~ short video download (save to photo album)

自己创建一个时间拦截器

Tiktok practice ~ homepage video ~ pull-down refresh

抖音实战~搜索页面~扫描二维码

抖音实战~分享模块~复制短视频链接

抖音实战~分享模块~短视频下载(保存到相册)

50 lines of code to crawl TOP500 books and import TXT documents

mongoDB的三种基础备份方法

Web resource preloading - production environment practice
随机推荐
Bonne Recommandation: développer des outils de sécurité pour les terminaux mobiles
超分之VRT
Three basic backup methods of mongodb
When are global variables initialized before entering the main function?
Six necessary threat tracking tools for threat hunters
Wechat applet custom pop-up components
商品秒杀系统
一些基本错误
What are the specific steps for opening a stock account? Is it safe to open an account online?
Case description: the competition score management system needs to count the competition scores obtained by previous champions and record them in the file. The system has the following requirements: -
Basic and necessary common plug-ins of vscade
论数据库的传统与未来之争之溯源溯本----AWS系列专栏
Convex hull problem
好物推薦:移動端開發安全工具
The two files are merged into a third file.
知识点总结
mongoDB的三种基础备份方法
抖音实战~分享模块~短视频下载(保存到相册)
stm32和电机开发(直流有刷电机和步进电机)
8VC Venture Cup 2017 - Final Round C. Nikita and stack