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;
        }
    };
  • 相关阅读:
    .NET ------ 多线程的简单使用
    .NET --- 页面刷新(html 和 js两种方式)
    .NET ---- B/S的特点,不接收js赋值
    二分查找与二分答案
    c++运行程序 鼠标点击按钮 (c++)(windows)
    c++运行程序 光标隐藏与移动 (c++)(windows)
    推荐:史蒂芬霍金论天道
    LaTeX公式学习
    Markdown语法学习
    文言语言!!!(附c/c++自译)
  • 原文地址:https://www.cnblogs.com/amadis/p/6654288.html
Copyright © 2011-2022 走看看