LeetCode第30题:Substring with Concatenation of All Words(Java实现)

题目:

LeetCode第30题:Substring with Concatenation of All Words(Java实现)_第1张图片

废话不多说,直接贴代码

class Solution {
    public List findSubstring(String s, String[] words) {
        List ret=new LinkedList<>();
        int size=words.length;
        if(size==0) return ret;
        Map wordsMap=new HashMap<>(size);
        for(String word:words)
            wordsMap.put(word,wordsMap.getOrDefault(word,0)+1);
        int wordLen=words[0].length();
        int window=size*wordLen;
        char[] charArray=s.toCharArray();
        int slength=charArray.length;
        for(int i=0;i map=new HashMap<>(size);
               // int hit = 0;
                int go = j+window-wordLen;
                for(int k=size-1;k>=0;--k){
                    String word=new String(charArray,go,wordLen);
                    int count=map.getOrDefault(word,0)+1;
                    int num = wordsMap.getOrDefault(word,0);
                    if(count>num){
                        j = go;
                       // map.clear();
                      //  hit = size-k;
                        break;
                    }else if(k==0){
                        ret.add(j);
                       // hit = 0;
                       // map.clear();
                    }else{
                        map.put(word,count);
                    }
                    
                    go -= wordLen;
                }
            }
        }
        return ret;
    }
}

运行结果:

LeetCode第30题:Substring with Concatenation of All Words(Java实现)_第2张图片

你可能感兴趣的:(LeetCode习题集,LeetCode习题集)