30 Substring with Concatenation of All Words
2015-09-09 20:33
417 查看
题目链接:https://leetcode.com/problems/substring-with-concatenation-of-all-words/
题目:
解题思路
自己想的方法效率比较低。但还是想记录下来。
采取滑动窗口的策略
每次从原字符串取出一个长度为需要匹配的所有单词长度的子串。
这个子串的第一个字符依次为原字符串的第 0 个,第 1 个,第 2 个,以此类推。
把要匹配的单词都放入map中(键为单词本身,值为单词个数),若有重复,值为 2。
将子串切分为需要匹配的单词的个数。
每次从子串中取出一个单词和 map 中的键值匹配
匹配中就从 map 中移除这个单词,没有匹配中就说明该子串不符合要求,跳出本次循环,继续找下一个子串。
若 map 已为空,说明该子串符合要求,用 list 记录下它的起始下标。
网上参考:/article/1378344.html
方法类似,但执行时间少很多。
题目:
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).
解题思路
自己想的方法效率比较低。但还是想记录下来。
采取滑动窗口的策略
每次从原字符串取出一个长度为需要匹配的所有单词长度的子串。
这个子串的第一个字符依次为原字符串的第 0 个,第 1 个,第 2 个,以此类推。
把要匹配的单词都放入map中(键为单词本身,值为单词个数),若有重复,值为 2。
将子串切分为需要匹配的单词的个数。
每次从子串中取出一个单词和 map 中的键值匹配
匹配中就从 map 中移除这个单词,没有匹配中就说明该子串不符合要求,跳出本次循环,继续找下一个子串。
若 map 已为空,说明该子串符合要求,用 list 记录下它的起始下标。
public class Solution { public List<Integer> findSubstring(String s, String[] words) { List<Integer> list = new ArrayList(); if(s == null || words == null || words.length == 0) return list; HashMap<String, Integer> map = new HashMap(); for(String word : words) { if(map.containsKey(word)) map.put(word, map.get(word) + 1); else map.put(word, 1); } int len = words[0].length(); int subStringLen = words.length * len; for(int k = 0; k <= s.length() - subStringLen; k ++) { String subString = s.substring(k, k + subStringLen); HashMap<String, Integer> mapTemp = new HashMap(map); for(int i = 0; i < words.length; i ++) { String word = subString.substring(i * len, (i + 1) * len); if(!mapTemp.isEmpty()) { if(mapTemp.containsKey(word)) { if(mapTemp.get(word) == 1) mapTemp.remove(word); else mapTemp.put(word, mapTemp.get(word) - 1); } else break; } if(mapTemp.isEmpty()) { list.add(k); break; } } } return list; } }
169 / 169 test cases passed. Status: Accepted Runtime: 836 ms
网上参考:/article/1378344.html
方法类似,但执行时间少很多。
相关文章推荐
- 数组指针、指针数组、地址的强制转换内存布局
- MVC之重定向
- 修改的bug记录
- 使用HTTP_X_FORWARDED_FOR获取客户端IP的严重后果
- BC水题--The Factor(质因分解)
- Testlink的学习总结
- POJ_3281_Dining(最大流dinic模板)
- poj 3280
- 学习matlab 1
- 国家模式c++
- keil4中逻辑分析仪使用
- PS技巧记录
- 联考1day2总结
- 进程与线程的区别和联系
- hdu 5012__Dice
- Uva-1347 Power Calculus
- Linux2.6.32内核笔记(2)内存管理子系统
- this关键字:
- db2使用Java存储过程实现MD5函数
- 误mlogc.c:32:23: error: curl/curl.h: No such file or directory