您的位置:首页 > 其它

30 Substring with Concatenation of All Words

2015-09-09 20:33 417 查看
题目链接:https://leetcode.com/problems/substring-with-concatenation-of-all-words/

题目:

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

方法类似,但执行时间少很多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: