leetcode30——串联所有单词的字串

滑动窗口的思想,将所有子串分为单词长度个元组,作为遍历的外层循环。

内层循环跨度为单词的长度

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer>result=new ArrayList<Integer>();

        int wordNum=words.length;
        if(wordNum==0)
            return result;
        int wordLen=words[0].length();
        HashMap<String,Integer>hashMap1=new HashMap<String,Integer>();
        for(String word:words)
        {
            if(hashMap1.containsKey(word))hashMap1.put(word,hashMap1.get(word)+1);
            else hashMap1.put(word,1);
        }
        //分成wordLen类情况
        for(int j=0;j<wordLen;j++)
        {
            HashMap<String,Integer>hashMap2=new HashMap<String,Integer>();
            int num=0;//记录当前HashMap2中有多少个单词与HashMap1匹配
            for(int i=j;i<s.length()-wordNum*wordLen+1;i+=wordLen)
            {
                boolean hasRemoved=false;   //防止情况三移除后,情况一继续移除
                while(num<wordNum){
                    String word=s.substring(i+num*wordLen,i+(num+1)*wordLen);
                    if(hashMap1.containsKey(word)){
                        int value=hashMap2.getOrDefault(word,0);
                        hashMap2.put(word,value+1);
                        if(hashMap2.get(word)>hashMap1.get(word))
                        {
                            hasRemoved=true;
                            int removeNum=0;
                            while(hashMap2.get(word)>hashMap1.get(word))
                            {
                                String curWord=s.substring(i+removeNum*wordLen,i+(removeNum+1)*wordLen);
                                int v=hashMap2.get(curWord);
                                hashMap2.put(curWord,v-1);
                                removeNum++;
                            }
                            num=num-removeNum+1;      
                            i=i+(removeNum-1)*wordLen;
                            break;
                        }
                    }
                    else    //情况二,当前单词不在hashMap1
                    {
                        hashMap2.clear();
                        i=i+num*wordLen;
                        num=0;
                        break;
                    }
                    num++;
                }
                if(num==wordNum) result.add(i);
                if(num==wordNum&&!hasRemoved)
                {
                    String firstWord=s.substring(i,i+wordLen);
                    int v=hashMap2.get(firstWord);
                    hashMap2.put(firstWord,v-1);
                    num=num-1;
                }
            }
        }
        return result;
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值