Substring with Concatenation of All WordsTotal
2014-08-29 13:37
381 查看
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).
代码:
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:
"barfoothefoobarman"
L:
["foo", "bar"]
You should return the indices:
[0,9].
(order does not matter).
代码:
import java.util.*; public class Solution_26 { public static List<Integer> findSubstring(String S, String[] L) { List<Integer> result = new ArrayList<Integer>(); Map<String, Integer> words = new HashMap<String, Integer>(); Map<String, Integer> tmp = new HashMap<String, Integer>(); for(int i = 0; i < L.length; i++) { if(!words.containsKey(L[i])) words.put(L[i], 1); else { int val = words.get(L[i]) + 1; words.put(L[i], val); } } int wordNum = L.length; int wordLen = L[0].length(); for(int i = 0; i <= S.length() - wordNum * wordLen; i++) { tmp.clear(); int j; for(j = 0; j < wordNum; j++) { String str = S.substring(i + j * wordLen, i + j * wordLen + wordLen); if(!words.containsKey(str)) break; if(!tmp.containsKey(str)) tmp.put(str, 1); else { int val = tmp.get(str) + 1; tmp.put(str, val); } if(tmp.get(str) > words.get(str)) break; } if(j == wordNum) result.add(i); } return result; } public static void main(String[] args) { // TODO Auto-generated method stub String[] str = {"foo","bar"}; System.out.println(findSubstring("barfoothefoobarman", str)); } }
相关文章推荐
- 【LeetCode】Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words *HARD*
- leetcode 71: Substring with Concatenation of All Words
- 天题之滑动窗口Substring with Concatenation of All Words
- 30. Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- Substring with Concatenation of All Words
- [LeetCode]030-Substring with Concatenation of All Words
- 【LeetCode算法练习(C++)】Substring with Concatenation of All Words
- 【LeetCode】Substring with Concatenation of All Words 解题报告
- leetCode 30.Substring with Concatenation of All Words (words中所有子串相连) 解题思路和方法
- leetcode 30 Substring with Concatenation of All Words
- LeetCode(30) Substring with Concatenation of All Words
- [LeetCode][Java] 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
- Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words暴力法暴力法更加暴力的方法