zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Navicat将表转为模型
    RestTemplate Hashmap变为LinkedHashMap源码解读
    IDEA无法编译源码,IDEA查看源码出现/* compiled code */
    grep,egrep,正则表达式
    特殊权限
    更新系统硬件信息----光驱
    复制其他文件的权限做为自己的权限
    umask
    生成随机口令
    让新增用户默认拥有文件
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9763885.html
Copyright © 2011-2022 走看看