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;
        }
    };
  • 相关阅读:
    js 左键点击页面时显示“您好”,右键点击时显示“禁止右键”。并在2分钟后自动关闭页面。
    搜藏 SQL
    邮件发送 图片
    超市购物打印小票的简单程序 记录下来
    KFC打印
    printf和scanf对于各种格式说明符
    Unity3d Camera size
    C#笔记
    CSV文件读写注意
    cocos2dx相关网址
  • 原文地址:https://www.cnblogs.com/amadis/p/6654288.html
Copyright © 2011-2022 走看看