您的位置:首页 > 其它

LeetCode 笔记系列七 Substring with Concatenation of All Words

2013-07-06 11:29 507 查看
题目: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).

这道题想了蛮久,主要是coding过程中老是出一些边界的错误。第一眼看到,立(zi)马(zuo)想(cong)到(ming)的解法是不是可以用bit位来表示L中的各个key呀,不同的key代表不同的位,然后通过扫描S,通过与操作确定各个bit位是不是在长度为L的substring中。结果写了一会发现问题是,L中有可能有相等的字符串哦。。。那在搜索S的时候就悲剧了不是。

一个折中的方法是,对每个key在L中的,保存一个list,例如有L=["foo","bar","foo"],那我们做这样一个hash哇:

foo: 0->1

bar: 2

然后在搜索S的时候顺次检查一个bitset。代码如下:

解法一:

public static ArrayList<Integer> findSubstring3(String S, String[] L) {
int lengthPerKey = L[0].length();
int numberOfKeys = L.length;
HashMap<String, Integer> map = new HashMap<String, Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
for(String str : L){
if(!map.containsKey(str)){
map.put(str, 1);
}else {
map.put(str, map.get(str) + 1);
}
}

for(int i = 0; i <= S.length() - numberOfKeys*lengthPerKey; i++){
int j = 0;
int st = i;
HashMap<String, Integer> wordsCount = new HashMap<String, Integer>(map);
for(j = 0; j < numberOfKeys;j++){
if(S.length() - st < (numberOfKeys - j)*lengthPerKey) break;
String sub = S.substring(st,st+lengthPerKey);
if(wordsCount.containsKey(sub)){
int times = wordsCount.get(sub);
if(times == 1) wordsCount.remove(sub);
else wordsCount.put(sub, times - 1);
}else break;
st += lengthPerKey;
}
if(j == numberOfKeys){
result.add(i);
}
}
return result;
}


View Code
例如L=["foo","bar","foo"],我们的hash是这样的:

foo: 2

bar: 1

然后对S中每一个固定长度的substring做计数。

总结:

1.如果你用了超过3个(包括3个)复杂数据结构,应该思考是不是自己想多了

2.想多了会[b]毁[/b]了你。

3.不要装b,先理解问题再想解法而不是为了用某个算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: