1. 程式人生 > 實用技巧 >30. 串聯所有單詞的子串 Substring with Concatenation of All Words

30. 串聯所有單詞的子串 Substring with Concatenation of All Words

You are given a stringsand an array of stringswordsofthe same length. Returnall starting indices of substring(s) insthat is a concatenation of each word inwordsexactly once,in any order,andwithout any intervening characters.

You can return the answer inany order.

Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

方法:

注意words陣列的長度都是一樣的,這樣可以簡化查詢

將words裡的元素放到map裡,s按照word長度擷取,放到另外一個map

兩個map相等則返回起始位置

public List<Integer> findSubstring(String s, String[] words) {
        List<Integer>  ans = new ArrayList<>();
        if(s == null || words == null || words.length == 0){
            return ans;
        }
        
int len = words[0].length(); Map<String,Integer> map = new HashMap<>(); for (String word : words){ if (map.containsKey(word)){ map.put(word, map.get(word) + 1); }else{ map.put(word, 1); } }
for (int i = 0; i < s.length() - words.length * len + 1; i++){ Map<String,Integer> map_s = new HashMap<>(); for (int j = 0; j < words.length * len; j += len){ if (!map.containsKey(s.substring(i+j,i+j+len))) break; if (map_s.containsKey(s.substring(i+j,i+j+len))){ map_s.put(s.substring(i+j,i+j+len), map_s.get(s.substring(i+j,i+j+len)) + 1); }else{ map_s.put(s.substring(i+j,i+j+len), 1); } } if (map.equals(map_s)) ans.add(i); } return ans; }

參考連結:

https://leetcode.com/problems/substring-with-concatenation-of-all-words/

https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/