java 30.具有所有Words.java的连接的子串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 30.具有所有Words.java的连接的子串相关的知识,希望对你有一定的参考价值。

//"barfoofoobarthefoobarman" ["bar","foo","the"]
public class Solution {
  public List<Integer> findSubstring(String s, String[] words) {
      List<Integer> res = new ArrayList<Integer>();
      if (words == null || words.length == 0 || s.length() < words.length * words[0].length()) return res;
      
      int count = words.length;
      int k = words[0].length();
      int len = s.length();
      
      HashMap<String, Integer> dict = new HashMap<String, Integer>();
          for (String word : words){
              dict.put(word, dict.containsKey(word) ? dict.get(word) + 1 : 1);
          }
          
      HashMap<String, Integer> dictCopy = new HashMap<String, Integer>();
      
      for(int i = 0; i < k; i++){
          int start = i;
          int end = i;
          count = words.length;//!!!
          dictCopy.clear();//!!!
          while(end + k <= s.length()){
              String temp = s.substring(end, end + k);
              if(dict.containsKey(temp)){
                  dictCopy.put(temp, dictCopy.containsKey(temp) ? dictCopy.get(temp) + 1 : 1);
                  count--;
                  while(dictCopy.get(temp) > dict.get(temp)){
                      String tempLeft = s.substring(start, start + k);
                      dictCopy.put(tempLeft, dictCopy.get(tempLeft) - 1);
                      start += k;
                      count++;
                  }
                  if(count == 0){
                      res.add(start);
                      String tempLeft = s.substring(start, start + k);
                      dictCopy.put(tempLeft, dictCopy.get(tempLeft) - 1);
                      start += k;
                      count++;
                  }
              } else {
                  count = words.length;
                  dictCopy.clear();
                  start = end + k;
              }
              end += k;
          }
      }
      return res;
  }
}

以上是关于java 30.具有所有Words.java的连接的子串的主要内容,如果未能解决你的问题,请参考以下文章

java 30.具有所有Words.java的连接的子串

java 30.具有所有Words.java的连接的子串

java 30.具有所有Words.java的连接的子串

java 30.具有所有Words.java的连接的子串

爬虫大作业

LINQ:具有多个条件的左外连接