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)
  • 相关阅读:
    正则表达式
    webfrom 母版页
    repeater的command事件用法
    JVM进程cpu飙高分析
    @Transactional导致无法动态数据源切换
    mysql分页查询优化(索引延迟关联)
    MAC下安装Homebrew 和 @权限的问题
    RabbitMQ安装以及集群部署
    RabbitMQ 延时消息队列
    java 实现生产者-消费者模式
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9763885.html
Copyright © 2011-2022 走看看