LeetCode29: Substring with Concatenation of All Words
2013-02-24 12:28
281 查看
You are given a string, S, and a list of words, L,
that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S:
L:
You should return the indices:
(order does not matter).
that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S:
"barfoothefoobarman"
L:
["foo", "bar"]
You should return the indices:
[0,9].
(order does not matter).
public class Solution { public ArrayList<Integer> findSubstring(String S, String[] L) { // Start typing your Java solution below // DO NOT write main() function HashMap<String, Integer> words = new HashMap<String, Integer>(); HashMap<String, Integer> found = new HashMap<String, Integer>(); ArrayList<Integer> res = new ArrayList<Integer>(); if(S==null || L==null) return res; // count all words in input list for(String str:L){ if(words.get(str) == null) words.put(str, 1); else words.put(str, words.get(str)+1); } int N=S.length(); int M=L.length; int wordLen = L[0].length(); for(int i=0; i<=N-M*wordLen; i++){ found.clear(); int j; for(j=0; j<M; j++){ String curStr = S.substring(i+j*wordLen, i+(j+1)*wordLen); if(words.get(curStr) == null) break; int expectedCount = words.get(curStr); int foundCount = found.get(curStr)==null?1:found.get(curStr)+1; if(expectedCount<foundCount) break; found.put(curStr, foundCount); } if(j==M) res.add(i); } return res; } }
相关文章推荐
- LeetCode 29 Substring with Concatenation of All Words
- LeetCode 29. Substring with Concatenation of All Words
- [LeetCode-Algorithms-30] "Substring with Concatenation of All Words" (2017.9.22-WEEK3)
- 【LeetCode】Substring with Concatenation of All Words
- LeetCode 30 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
- [leetcode 30] Substring with Concatenation of All Words
- Leetcode(10) - Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- leetcode 30. Substring with Concatenation of All Words
- leetcode--30. Substring with Concatenation of All Words
- 【LeetCode】30. Substring with Concatenation of All Words
- LeetCode 30 - 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 30 Substring with Concatenation of All Words