您的位置:首页 > 编程语言 > Java开发

[Leetcode] Substring with Concatenation of All Words (Java)

2013-12-28 20:18 459 查看
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).

题意:给定一个字符串S,并且给定一个单词集合L,每个单词长度相等。找到S的子串等于L所有单词的集合(每个单词出现且仅出现一次,但是L中单词允许重复),不含有别的字母(即若L=["ab","cd","ab"],那么找到的S子串可能为”abcdab“,”ababcd“,”cdabab“,但是”abccdab“与”abcd“则不行),找出所有这样的S子串,并返回每一个子串的初始坐标值。

hash的办法,若L=["ab","cd","ab"],则 map为:("ab",2),("cd",1)

从S中找是否含有所有的map内容,若中间出现多余单词或字母,则i++开始下次查找,若未出现其余字母与单词,则将i 加入到list中。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SubstringwithConcatenationofAllWords {
public ArrayList<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(L.length<1)
return list;
int wordLen = L[0].length();
Map<String, Integer> map = new HashMap<String, Integer>();
for(String s : L) {
if(!map.containsKey(s))
map.put(s, 1);
else {
map.put(s, map.get(s)+1);
}
}
boolean flag ;
for(int i=0;i<=S.length()-L.length*wordLen;i++){
int start = i;
Map<String, Integer> temp = new HashMap<String, Integer>(map);
flag = false;
while(start-i<L.length*wordLen){
flag = true;
String string = S.substring(start,start+wordLen);
if(temp.containsKey(string)&&temp.get(string)>0)
temp.put(string, temp.get(string)-1);
else {
flag = false;
break;
}
start+=wordLen;
}
if(flag){
list.add(i);
}
}
return list;
}
public static void main(String[] args) {
String[] L = {"a","b"};
String S = "aaa";
for(Integer i : new SubstringwithConcatenationofAllWords().findSubstring(S, L)){
System.out.print(i+",");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: