leetcode 30 Substring with Concatenation of All Words

lc30 Substring with Concatenation of All Words

Two hashmap

After the match to make a record number of occurrences of words [] of each word, used

A source string used to record the i ~ j occurrences of each word, and the ratio of the former

The idea is to check the source string length of all consecutive words []. Length () * words [0] .length substring

for(i=0; i<s.length() - words.length()*words[0].length; i++)

 

 1 class Solution {
 2     public List<Integer> findSubstring(String s, String[] words) {
 3         if(s.length() == 0 || words.length == 0)
 4             return new ArrayList<Integer>();
 5         HashMap<String, Integer> count = new HashMap<>();
 6         
 7         for(String i : words)
 8             count.put(i, count.getOrDefault(i, 0) + 1);
 9         int len = words[0].length();
10         int wordsNum = words.length;
11         List<Integer> res = new ArrayList<>();
12         
13         for(int i=0; i<s.length() - len*wordsNum + 1; i++){
14             HashMap<String, Integer> seenWords =  new HashMap<>();
15             int j = 0;
16             while(j < wordsNum){
17                 String word = s.substring(i + j*len, i + (j+1)*len);
18                 if(count.containsKey(word)){
19                     seenWords.put(word, seenWords.getOrDefault(word, 0) + 1);
20                     if(seenWords.get(word) > count.get(word))
21                          break;
22                 
23                 }else
24                     break;
25                 j++;
26             }
27             if(j == wordsNum){
28                 res.add(i);
29             }
30         }
31         return res;
32     }
33 }

 

Guess you like

Origin www.cnblogs.com/hwd9654/p/10992697.html