zoukankan      html  css  js  c++  java
  • [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) in s that is a concatenation of each word in words exactly once and without any intervening characters.

    For example, given:
    s: "barfoothefoobarman"
    words: ["foo", "bar"]

    You should return the indices: [0,9].
    (order does not matter).

    // 
    class Solution {
        void helper(string s, int lenword, int totallen, unordered_map<string, int>& ht, unordered_map<string, int>& ht_bk, vector<int>& allsol){
    
            for (int i = 0; i<= s.size() - totallen; i++){
                int j;
                for (j = i; j <= i + totallen - lenword; j += lenword){
                    string tmp = s.substr(j, lenword);
                    //if (ht.count(tmp) && ht[tmp] > 0 ){
                    if (ht[tmp] > 0 ){
                        ht[tmp]--;
                    }else{
                        break;
                    }
                }
                // !! to clear the ht
                ht = ht_bk;
    
                if (j == i + totallen){
                    allsol.push_back(i);
                }
            }
            
            return;
        }
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            vector<int> allsol;
            int sol = 0;
            int start;
            
            if (words.empty() || s.empty()) return allsol;
            
            unordered_map<string, int> ht;
            unordered_map<string, int> ht_bk;
            int n = s.size();
            int lenword = words[0].size();
            int ntotalwords = words.size();
            int totallen = ntotalwords * lenword;
            if (n < totallen) return allsol;
            
            for (int i = 0; i < words.size(); i++){
                ht[words[i]]++;
            }
            ht_bk = ht;
            
            helper(s, lenword, totallen, ht, ht_bk,allsol);
            
            return allsol;
        }
    };
  • 相关阅读:
    tuple元组
    list列表
    OS模块
    time模块/datetime模块/calendar模块
    Codeforces Round #196 (Div. 2)
    【HDU 2853】 KM算法
    【HDU1914 The Stable Marriage Problem】稳定婚姻问题
    【HDU4585 Shaolin】map的经典运用
    【HDU4578 Transformation】线段树
    【HDU4632 Palindrome subsequence】区间dp
  • 原文地址:https://www.cnblogs.com/amadis/p/6654288.html
Copyright © 2011-2022 走看看