1. 程式人生 > >Substring with Concatenation of All Words:判斷目標串包含排列組合的模式串的起始位置

Substring with Concatenation of All Words:判斷目標串包含排列組合的模式串的起始位置

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

Example 1:

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

Example 2:

Input:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
Output: []

思路:最初的思路是排列組合出所有模式串的可能,然後根據目標串逐個匹配,但是不能通過所有樣例,因為會超時。

所以,借鑑了:https://leetcode.com/problems/substring-with-concatenation-of-all-words/discuss/13656/An-O(N)-solution-with-detailed-explanation的思路:利用窗的思想,固定目標串s,然後滑動匹配,同時利用了所有模式串長度相同的性質,下面是他的程式碼:

 // travel all the words combinations to maintain a window
    // there are wl(word len) times travel
    // each time, n/wl words, mostly 2 times travel for each word
    // one left side of the window, the other right side of the window
    // so, time complexity O(wl * 2 * N/wl) = O(2N)
    vector<int> findSubstring(string S, vector<string> &L) {
        vector<int> ans;
        int n = S.size(), cnt = L.size();
        if (n <= 0 || cnt <= 0) return ans;
        
        // init word occurence
        unordered_map<string, int> dict;
        for (int i = 0; i < cnt; ++i) dict[L[i]]++;
        
        // travel all sub string combinations
        int wl = L[0].size();
        for (int i = 0; i < wl; ++i) {
            int left = i, count = 0;
            unordered_map<string, int> tdict;
            for (int j = i; j <= n - wl; j += wl) {
                string str = S.substr(j, wl);
                // a valid word, accumulate results
                if (dict.count(str)) {
                    tdict[str]++;
                    if (tdict[str] <= dict[str]) 
                        count++;
                    else {
                        // a more word, advance the window left side possiablly
                        while (tdict[str] > dict[str]) {
                            string str1 = S.substr(left, wl);
                            tdict[str1]--;
                            if (tdict[str1] < dict[str1]) count--;
                            left += wl;
                        }
                    }
                    // come to a result
                    if (count == cnt) {
                        ans.push_back(left);
                        // advance one word
                        tdict[S.substr(left, wl)]--;
                        count--;
                        left += wl;
                    }
                }
                // not a valid word, reset all vars
                else {
                    tdict.clear();
                    count = 0;
                    left = j + wl;
                }
            }
        }
        
        return ans;
    }

我用java改寫了一下,當移除多餘詞時,一定要注意當前有效詞數目nWordNum的條件,這個位置太容易出錯了!!!!!!

class Solution {
    Map<String,Integer> dic = new HashMap<String,Integer>();
    public List<Integer> findSubstring(String s, String[] words) {
        if(s == null || s.length() <= 0 || words.length <= 0) return new ArrayList<Integer>();
        int allWordNum = 0;
        List<Integer> ans = new ArrayList<Integer>();
        for(String word : words){
            int count = (dic.get(word)==null)?0:dic.get(word);
            dic.put(word,count + 1);
            allWordNum++;
        }
        int wordLen = words[0].length();
        for(int i = 0 ; i < wordLen ; i++){//起點位置,視窗左界起點
            Map<String,Integer> ndic = new HashMap<String,Integer>();
            int left = i;//視窗左界
            int nWordNum = 0;
            for(int j = left + wordLen; j <= s.length(); j += wordLen){//視窗右界
                String word = s.substring(j - wordLen,j);
                //System.out.println("word : "+word);
                if(dic.containsKey(word)){
                    int c = (ndic.get(word)==null)?0:ndic.get(word);
                    ndic.put(word,c + 1);
                   // System.out.println("word count: "+ndic.get(word));
                    //System.out.println("dic.get(word) : "+word+" : " +dic.get(word));
                    if(ndic.get(word) <= dic.get(word)){
                        nWordNum++;
                        //System.out.println("nWordNum : "+nWordNum);
                    }else{

                    	
                        while(ndic.get(word) > dic.get(word)){
                            String delWord = s.substring(left,left + wordLen);
                            ndic.put(delWord,ndic.get(delWord) - 1);
                            if(ndic.get(delWord) != dic.get(delWord)){//移除的並非是剛剛新增到當前字典中的多餘的詞,所以有效數目減少
                                nWordNum--;
                            }
                            left += wordLen;
                        }
                        //System.out.println("after while : "+nWordNum);
                    }
                    if(nWordNum == allWordNum){
                        ans.add(left);
                        //System.out.println("allWordNum : "+allWordNum);
//                       
//                        System.out.println("j : "+j);
                        String visitedWord = s.substring(left,left + wordLen);
                        ndic.put(visitedWord,ndic.get(visitedWord) - 1);
                        left += wordLen;
                        nWordNum--;
                        //System.out.println("nWordNum : "+nWordNum);
//                        System.out.println("left : " + left);
//                        System.out.println(visitedWord);
//                        System.out.println("nWordNum : "+nWordNum);
//                        System.out.println(ndic.get(visitedWord));
                    }
                }else{
                    ndic.clear();
                    left = j;
                    nWordNum = 0;
                }
            }
        }
        return ans;
    }
}

相關推薦

Substring with Concatenation of All Words判斷目標包含排列組合模式起始位置

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s tha

每日算法之二十六Substring with Concatenation of All Words

i++ 清空 article 多個 串匹配 -m ++ 每次 class 變相的字符串匹配 給定一個字符串,然後再給定一組同樣長度的單詞列表,要求在字符串中查找滿足下面條件的起始位置: 1)從這個位置開始包括單詞列表中全部的單詞。且每一個單詞僅且必須出現一次。 2)在出

LeetCode題解Substring with Concatenation of All Words

題目要求 You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(

LeetCode30. Substring with Concatenation of All Words

問題描述: 30. 與所有單詞相關聯的字串 給定一個字串s和一些長度相同的單詞words。在s中找出可以恰好串聯 words中所有單詞的子串的起始位置。 注意子串要與words中的單詞完全匹配,中間不能有其他字元,但不需要考慮words中單詞串聯的順序。 示例

[Leetcode] Substring with concatenation of all words 串聯所有單詞的子

一聲 count 博客 oot 之間 back 空格 理解 是不是 You are given a string, S, and a list of words, L, that are all of the same length. Find all starting i

30. Substring with Concatenation of All Words

n) 尋找 log return 給定 equals key brush art 所有的循環只為尋找答案, 所有的判斷只為選擇正確答案 public List<Integer> findSubstring(String s, String[] words) {

LeetCode HashTable 30 Substring with Concatenation of All Words

should pub str key integer ash arraylist nat character You are given a string, s, and a list of words, words, that are all of the same le

leetcode python 030 Substring with Concatenation of All Words

bsp 索引 ring == return rds nat 長度 all ## 您將獲得一個字符串s,以及一個長度相同單詞的列表。## 找到s中substring(s)的所有起始索引,它們只包含所有單詞,## eg:s: "barfoothefoobarman" words

【python/leetcode/Hard】Substring with Concatenation of All Words

題目 基本思路 使用一個字典統計一下words中每個單詞的數量。由於每個單詞的長度一樣,以題中給的例子而言,可以3個字母3個字母的檢查,如果不在字典中,則break出迴圈。有一個技巧是建立一個臨時字典currDict,用來統計s中那些在words中的單詞的數量,必須和wor

30.substring-with-concatenation-of-all-words

        說實在的,這道題還是比較難的,因為沒有好的思路,其實從歷年各個公司的演算法真題來看,難題還是多出現在字串上,這道題就是比較靈活的一道,沒啥太好的思路,起初想著dfs,倒是可以做,但是開銷蠻大的,因此,這裡我參考大神的程式碼寫了使用hash來解決

4.4.2 python 字串雙指標/雜湊演算法2 —— Substring with Concatenation of All Words & Group Anagrams

這兩道題目都很巧妙的應用了雜湊演算法,可以作為雜湊演算法的應用講解,後面介紹雜湊的時候就不再做題了哈。 30. Substring with Concatenation of All Words You are given a string, s, and a list of wor

【LeetCode】30. Substring with Concatenation of All Words - Java實現

文章目錄 1. 題目描述: 2. 思路分析: 3. Java程式碼: 1. 題目描述: You are given a string, s, and a list of words, words, that are all of t

Leetcode之Substring with Concatenation of All Words

題目: You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in&n

【LeetCode】30. Substring with Concatenation of All Words(C++)

地址:https://leetcode.com/problems/substring-with-concatenation-of-all-words/ 題目: You are given a string, s, and a list of words, words, that ar

Substring with Concatenation of All Words -- LeetCode

原題連結: http://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/這道題看似比較複雜,其實思路和Longest Substring Without Repeating Charact

Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concaten

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 i

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)

【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

LeetCode 30 — Substring with Concatenation of All Words(與所有單詞相關聯的字串)

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) i