LeetCode--030--串联所有单词的字串(java)

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

输入:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:
  s = "wordgoodgoodgoodbestword",
  words = ["word","good","best","word"]
输出:[]
 1 class Solution {
 2     public List<Integer> findSubstring(String s, String[] words) {
 3         if(s == null || words == null || words.length == 0)return  new ArrayList<>();
 4         List<Integer> res = new ArrayList<>();
 5         int n = words.length;
 6         int m = words[0].length();
 7         HashMap<String,Integer> map = new HashMap<>();
 8         for(String str: words){
 9             map.put(str,map.getOrDefault(str,0)+1);
10         }
11         for(int i = 0;i <= s.length() - n * m;i++){
12             HashMap<String,Integer> copy = new HashMap<>(map);
13             int k = n;
14             int j = i;
15             while(k > 0){
16                 String str = s.substring(j,j+m);
17                 if(!copy.containsKey(str) || copy.get(str) < 1){
18                     break;
19                 }
20                 copy.put(str,copy.get(str) - 1);
21                 k--;
22                 j += m;
23             }
24             if(k == 0)res.add(i);
25             
26         }
27         return res;
28     }
29 }

2019-04-23 17:31:31

原文地址:https://www.cnblogs.com/NPC-assange/p/10757716.html