您的位置:首页 > 其它

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:
"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));
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: