LeetCode进阶之路(Substring with Concatenation of All Words)
来源:互联网 发布:百度网盘显示网络异常 编辑:程序博客网 时间:2024/06/15 12:05
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
题目:给出一个字符串和一个字符串数组(其中每个字符串长度相等),数组中的字符串组成一个长串,找出字符串中和长串相等的子串,并输出其初始位置。
思路:因为字符串数组中每个元素长度都相等,就可以知道我们目标子串的长度。题目就简化成一个确定长度的字符串和一个数组中元素随机组成的串是否相等,那就可以把这个字符串也分割n个元素的数组,两个数组按顺序排列后比较是否相等即可。
public List<Integer> findSubstring(String s, String[] words) { int len = words[0].length()*words.length;//数组元素个数*每个长度 List<Integer> list = new ArrayList<Integer>(); List<String> list1 = new ArrayList<String>(); for(int i = 0; i < words.length;i++) { list1.add(words[i]);//把数组中的元素都放到list中,后面减小遍历范围有用 } for(int i = 0;i <= s.length() - len;i++){ String str = s.substring(i, i + len);//把字符串按len长度分割,如果就这样去判断会超时,因此要排除一些子串,缩小范围 if(list1.contains(str.substring(0, words[0].length()))){//把那些开头就不符合的串给排除。 if(find(str, words)){ list.add(i); } } } return list; } public boolean find(String str, String[] words) { String[] strWords = new String[words.length]; int len = words[0].length(); Arrays.sort(words);//数组按序排列 for(int i = 0; i < str.length()/len;i++){//把字符串分割,组成一个数组(根据words数组元素的长度来分割) strWords[i] = str.substring(i*len, i*len+len); } Arrays.sort(strWords);//两个数组排序后比较 for(int i = 0; i< words.length;i++){ if(!words[i].equals(strWords[i])){ return false; } } return true; }
0 0
- LeetCode进阶之路(Substring with Concatenation of All Words)
- LeetCode: Substring with Concatenation of All Words
- LeetCode : Substring with Concatenation of All Words
- [Leetcode] Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- LeetCode:Substring with Concatenation of All Words
- Leetcode: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words
- LeetCode | Substring with Concatenation of All Words
- LeetCode - Substring with Concatenation of All Words
- Substring with Concatenation of All Words -- LeetCode
- Leetcode: Substring with Concatenation of All Words
- leetcode:Substring with Concatenation of All Words
- ue4 选人工具
- 分析 设计 构造 区别
- (4)从零开始的操作系统开发日记
- hdu5545The Battle of Guandu
- VMware Centos6.5 网络配置
- LeetCode进阶之路(Substring with Concatenation of All Words)
- 设计模式-工厂模式
- Hive安装与使用
- [置顶] 在C#中使用SerialPort类实现串口通信(陆续更新)
- ue4-日志使用
- Linux内核分析。4
- Android中Context的传递
- 认识CoreData-高级用法
- stack/queue