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;
    }
};
posted @ 2017-03-17 16:11  aiterator  阅读(123)  评论(0编辑  收藏  举报