1. 程式人生 > >【LeetCode】Substring with Concatenation of All Words 解題報告

【LeetCode】Substring with Concatenation of All Words 解題報告

【題目】

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S"barfoothefoobarman"
L["foo", "bar"]

You should return the indices: [0,9]

.
(order does not matter).

【解析】

題意:給定一個字串S和一個字串陣列L,L中的字串長度都相等,找出S中所有的子串恰好包含L中所有字元各一次,返回子串的起始位置。

把L轉化為一個HashMap<String, Integer>,其value表示L中String的個數,因為L中可能包含相同的字串。

public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> ans = new ArrayList<Integer>();
        if (S.length() < 1 || L.length < 1) return ans;
        int len = L[0].length(); //題目說L中每個單詞長度一樣
        
        //初始化HashMap,注意L中可能包含多個相同的字串,所以用value表示個數
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (int j = 0; j < L.length; j++) {
            if (map.containsKey(L[j])) {
            	map.put(L[j], map.get(L[j]) + 1);
            } else {
            	map.put(L[j], 1);
            }
        }
        
        //i的範圍很關鍵,如果直接到S.length()是會超時的
        for (int i = 0; i <= S.length() - L.length * len; i++) {
            int from = i;
            String str = S.substring(from, from + len);
            int cnt = 0;
            while (map.containsKey(str) && map.get(str) > 0) {
                map.put(str, map.get(str) - 1);
                cnt++;
                from += len;
                if (from + len > S.length()) break; //注意越界
                str = S.substring(from, from + len);
            }
            
            //L中每個單詞恰好出現一次,加入到結果集
            if (cnt == L.length) {
                ans.add(i);
            }
            
            //為下一次初始化HashMap
            if (cnt > 0) {
            	map.clear();
                for (int j = 0; j < L.length; j++) {
                    if (map.containsKey(L[j])) {
                    	map.put(L[j], map.get(L[j]) + 1);
                    } else {
                    	map.put(L[j], 1);
                    }
                }
            }
        }
        
        return ans;
    }
}

這道題的Test Case有點變態,程式碼改了好多次,各種沒有注意到的邊邊角角。

=====================

Update on 2015/10/28

該題時間要求已變,上述程式碼會超時,等待後續更高效的解法,也歡迎大家補充好的解法。