30 Substring with Concatenation of All Words

30
Substring with Concatenation of All Words
19.6%
Hard
數words
數s.substring
都用HashMap

public class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> rst = new ArrayList<Integer>();
        if (words.length == 0) return rst;
        int wordLen = words[0].length();
        int subLen = wordLen * words.length;
        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        for (String word:words){
            if (countMap.containsKey(word)) countMap.put(word, countMap.get(word) + 1);
            else countMap.put(word, 1);
        }
        for (int i=0; i<s.length()-subLen+1; i++){
            HashMap<String, Integer> copyMap = (HashMap<String, Integer>)countMap.clone();
            for (int j=0; j<words.length; j++){
                String word = s.substring(i+j*wordLen, i+(j+1)*wordLen);
                if (copyMap.containsKey(word)){
                    if (copyMap.get(word) == 1) copyMap.remove(word);
                    else copyMap.put(word, copyMap.get(word)-1);
                }else break;
            }
            if (copyMap.isEmpty()) rst.add(i);
        }
        return rst;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容