• 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.

    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: []

    AC code:

    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            unordered_map<string, int> mario;
            vector<int> res={};
            int len1 = s.length(), num = words.size();
            if (len1 == 0 || num == 0) return res;
            int len2 = words[0].length();
            for (int i = 0; i < words.size(); ++i) {
                mario[words[i]]++;
            }
            for (int i = 0; i < len1-num*len2+1; ++i) {
                unordered_map<string, int> seen;
                int j = 0;
                for (; j < num; ++j) {
                    string word = s.substr(i+j*len2, len2);
                    if (mario.find(word) != mario.end()) {
                        seen[word]++;
                        if (seen[word] > mario[word])
                            break;
                    } else 
                        break;
                }
                if (j == num)
                    res.push_back(i);
            }
            return res;
        }
    };
    

    Runtime: 132 ms, faster than 49.73% of C++ online submissions for Substring with Concatenation of All Words.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    午餐
    Page Visibility API 页面是否获取焦点 Event: visibilitychange
    js dom 观察者属性 MutationObserver
    js substr和substring
    萌新 学习 vuex
    font-awesome图标转为图片
    如何用 CSS Animations 实现滑动图片展现文字的效果
    CSS3的变形、过渡、动画、关联属性
    用户网站访问速度慢详解
    CSS尺寸单位
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9763885.html
Copyright © 2020-2023  润新知