当前位置:网站首页>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;
}
边栏推荐
- 手机影像内卷几时休?
- 开户可以在网上开么?能安全吗?
- 项目实战四:用户登录及token访问验证(reids+jwt)
- Installation and use of filebeat
- DAPP丨LP单双币流动性质押挖矿系统开发原理分析及源码
- Filebeat安装及使用
- Project practice 5: build elk log collection system
- Uni app uses canvas to draw QR code
- Successfully solved the problem of garbled microservice @value obtaining configuration file
- 【推荐收藏】这8个常用缺失值填充技巧一定要掌握
猜你喜欢

Redis单点登陆系统+投票系统

Tiktok practice ~ sharing module ~ copy short video link

Introduction to single chip microcomputer one-on-one learning strategy, independent development program immediately after reading

数据库范式和主码的选择

Arduino UNO + DS1302利用31字节静态RAM存储数据并串口打印

Pinda general permission system (day 3~day 4)

Project practice 5: build elk log collection system

IK分词器

微服务架构

stm32和电机开发(直流有刷电机和步进电机)
随机推荐
Tiktok practice ~ sharing module ~ copy short video link
IK分词器
Analysis on development technology of NFT meta universe chain game system
品达通用权限系统(Day 1~Day 2)
C语言 文件光标 fseek
黑客用机器学习发动攻击的九种方法
Tree array
MySQL - database creation and management
品达通用权限系统(Day 3~Day 4)
论数据库的传统与未来之争之溯源溯本----AWS系列专栏
限流设计及实现
IK word breaker
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: -
Résumé des points de connaissance
MySQL - subquery usage
redis 基础知识
(几何) 凸包问题
Some cold knowledge about QT database development
Micro service single sign on system (SSO)
商品秒杀系统