您的位置:首页 > 其它

**LeetCode-Substring with Concatenation of All Words

2015-11-25 07:39 423 查看
首先记录一个map 数字典里面的word 每个出现几遍, 然后对于string 扫3遍 (假如word length是3)每次有一个offset开始

这样就能保证把每个情况错开的word都包含全

判断是否涵盖了dict里面所有词并且使用频率也对 是通过另一个map的每个词个数不可以超dict的map 并且总count等于dict里面词的个数

然后每次记录一个start 开始每个词假如另一个map 假如这个词属于dict 就加入map 加入这个词的数量没有超 count就加一

假如这个词的个数超了 就挪动开始的start 往后一个词一个词减去 直到这个词个数不超 注意其中count什么时候--

之后判断是否满足条件可以作为一个结果

注意每次碰到非字典词 或者一遍扫完 换一个offset的时候 map要清空

public class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List <Integer> res = new ArrayList<Integer>();
if ( s == null || s.length() == 0 || words == null )
return res;
int wordLen = words[0].length();
int num = words.length;
HashMap<String, Integer> hist = new HashMap<String, Integer>();
for ( int i = 0; i < num; i ++ ){
if ( hist.containsKey ( words [ i ] ) )
hist.put ( words[i], hist.get ( words[ i ]) + 1 );
else
hist.put ( words [i], 1 );
}
HashMap<String, Integer> map = new HashMap<String, Integer>();
for ( int i = 0; i < wordLen; i ++ ){
int count = 0;
int start = i;
for ( int cur = i; cur <= s.length() - wordLen; cur += wordLen ){
String temp = s.substring ( cur, cur + wordLen );
if ( hist.containsKey( temp )){
if ( map.containsKey( temp ) )
map.put ( temp, map.get ( temp ) + 1 );
else
map.put ( temp, 1 );
if ( map.get ( temp ) <= hist.get ( temp ))
count ++;
else{
while ( map.get (temp) > hist.get (temp) ){
String str = s.substring( start, start + wordLen );
map.put ( str, map.get ( str ) - 1 );
if ( hist.get ( str ) > map.get ( str ) )
count --;
start += wordLen;
}
}
if ( count == num ){
res.add ( start );
}
}
else{
map.clear();
count = 0;
start = cur + wordLen;
}
}
map.clear();
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: