leetcode: Substring with Concatenation of All Words

来源:互联网 发布:mysql 高并发version 编辑:程序博客网 时间:2024/05/17 04:04

由于L中的词长度都一样,大大方便了我们每次的循环判断。   思路就是先记录L中有那些词组,以及个字出现的次数。   之后从S头部开始每一个位置判断是否包含L中的全部词组。   如果出现不包含或是多包含就跳出,从下个位置重新开始判断。

这里使用HashMap记录键值对,方便更新。

public class Solution {    public ArrayList<Integer> findSubstring(String S, String[] L) {        ArrayList<Integer> res = new ArrayList<Integer>();        if( S==null || L==null || L.length==0 )        {            return res;        }        HashMap<String,Integer> words = new HashMap<String,Integer>();        for( int i=0;i<L.length;i++ )        {            if( words.containsKey(L[i]) )            {                int tmp = words.get(L[i]);                words.put(L[i],tmp+1);            }            else            {                words.put(L[i],1);            }        }        int wLen = L[0].length();        for( int i=0;i<=(S.length()-L.length*wLen);i++ )        {            HashMap<String,Integer> temp = new HashMap<String,Integer>(words);            int count=L.length;            int st=0;            while(st<count)            {                String str = S.substring(i+st*wLen,i+st*wLen+wLen);                if( !temp.containsKey(str) )                {                    break;                }                int num = temp.get(str);                if( num<=0 )                {                    break;                }                temp.put(str,num-1);                st++;            }            if( st==count )            {                res.add(i);            }        }        return res;    }}



0 0
原创粉丝点击