当前位置:网站首页>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;
}
边栏推荐
- MySQL stored procedure
- Some cold knowledge about QT database development
- 8VC Venture Cup 2017 - Final Round C. Nikita and stack
- On the origin of the dispute between the tradition and the future of database -- AWS series column
- Record of user behavior log in SSO microservice Engineering
- Deep learning: numpy
- Microservice architecture
- Development principle analysis and source code of dapp-lp single and dual currency liquidity pledge mining system
- 链游开发成品源码 链游系统开发详情说明
- 转:实事求是
猜你喜欢

Feign remote call

Project practice 5: build elk log collection system

手机影像内卷几时休?

Kubernetes resource topology aware scheduling optimization

(树) 树状数组

Some cold knowledge about QT database development

西瓜书重温(七): 贝叶斯分类器(手推+代码demo)

项目实战六:分布式事务-Seata

Xlua get button registration click event of ugui

Tiktok practice ~ search page ~ video details
随机推荐
What are the specific steps for opening a stock account? Is it safe to open an account online?
Separate save file for debug symbols after strip
vue中缓存组件keep-alive
xlua获取ugui的button注册click事件
On the escape of inequality value
Deep learning: numpy
redis 基础知识
读书笔记:《过程咨询 III》
Redis单点登陆系统+投票系统
Boot indicator monitoring
Tiktok practice ~ sharing module ~ generate short video QR code
(树) 树状数组
Unit test of boot
C语言 文件光标 fseek
Installation and use of logstash
When does the mobile phone video roll off?
mysql存储过程
Micro service single sign on system (SSO)
DAPP丨LP单双币流动性质押挖矿系统开发原理分析及源码
Introduction to single chip microcomputer one-on-one learning strategy, independent development program immediately after reading