0
点赞
收藏
分享

微信扫一扫

LeetCode 第30题

booksmg2014 2022-01-24 阅读 74

LeetCode 30题
在这里插入图片描述

class Solution {
   public static List<Integer> findSubstring(String s, String[] words) {
        List<Integer> resList = new ArrayList<>();
        int wordLength = words[0].length();
        Map<String, Integer> wordMap = new HashMap<>();
        Map<String, Integer> curMap = new HashMap<>();
        for (String w : words) {
            int value = wordMap.getOrDefault(w, 0);
            wordMap.put(w, value + 1);
        }

        for(int i = 0; i < s.length()-words.length*wordLength+1; i++){
            int j = i + wordLength;
            while (j-i <= words.length*wordLength && j <= s.length()){
                String substring = s.substring(j-wordLength, j);
                if(curMap.containsKey(substring)){
                    if(curMap.get(substring) < wordMap.get(substring)){
                        curMap.put(substring, curMap.get(substring)+1);
                    }else{
                        curMap.clear();
                        break;
                    }
                }else if(wordMap.containsKey(substring)){
                    curMap.put(substring, 1);
                }else {
                    curMap.clear();
                    break;
                }
                j += wordLength;
            }
            if(j-i-wordLength== words.length*wordLength && curMap.size() == wordMap.size()){
                resList.add(i);
            }
            curMap.clear();
        }
        return resList;
    }
}

在这里插入图片描述

举报

相关推荐

0 条评论