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

    题目意思就是说,一个字符串从一个字符数组里面匹配,如果字符串里面某一段能够将字符数组全部匹配,那么记录这段的开始下表。最后返回所有符合条件的下表。

    • 先将字符数组放入unordered_map中记录出现的次数
    • 枚举字符串每一个位置
    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            
            unordered_map<string, int> mp;
            for(size_t i = 0; i < words.size(); ++ i)
                mp[words[i]] ++;
            
            vector<int> vec;
            
            int l = words[0].size(), len = words.size() * l;
            for(size_t i = 0; i < s.size(); ++ i)
            {
                if(i+len-1 >= s.size())
                    break;
                
                unordered_map<string, int> mp1(mp);
                bool is = true;
                for(size_t j = 0; j < words.size(); ++ j)
                {
                    string str = s.substr(i+l*j, l);
                    if(mp1[str] == 0)
                    {
                        is = false;
                        break;
                    }
                    mp1[str] --;
                }
                if(is)
                    vec.push_back(int(i));
            }
            return vec;
        }
    };
    
  • 相关阅读:
    SeaweedFS上手使用指南
    XyTalk企业即时通讯IM开始开源
    大数据项目相关技术栈(Hadoop周边技术)
    Hive SQL基础操作
    Applet Mode
    快速开始
    NetBeans启动Tomcat报“'127.0.0.1' 不是内部或外部命令”启动失败的解决办法
    运行带distance field的Hiero
    Game Loop的几种实现方式
    20150408
  • 原文地址:https://www.cnblogs.com/aiterator/p/6566850.html
Copyright © 2020-2023  润新知