30. Substring with Concatenation of All Words

来源:互联网 发布:ip反查域名网站 编辑:程序博客网 时间:2024/06/15 00:19

Problem:

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].
(order does not matter).


这道题注意利用c++中map<string, int> my_map的特性。的特性。

例如:1.my_map.count(str)返回字典中是否有该string; 

           2.my_map[string]可存储该string的个数。

对于string,可以通过my_string.substr(i,word_length)获得子字符串。这些操作都可以简化代码。

解题思路为:根据words构造字典,键为字符串数组中的字符串,值为该字符串在字符串数组中出现的次数。暴力循环string,对于每个string,取子字符串,若在字典中存在,则该字符串的值减1,若所有值都为0了,则说明当前位置存在相应字符串,将该位置压入result中。否则重新初始化map。

class Solution {public:    void InitialMap(map<string,int>& my_Map,vector<string>& words)    {        for(int i=0; i<words.size(); i++)        {            my_Map[words[i]] +=1;        }    }        vector<int> findSubstring(string s, vector<string>& words) {        vector<int> result;        //构建map        map<string,int> my_Map;        InitialMap(my_Map, words);                //        int string_length = s.length();        int word_length = words[0].length();        int word_num = words.size();        //若字符串或者map为空,直接返回空        if(string_length == 0 || word_num == 0)            return result;                int change_flag = 0;//用于标记是否改变了map,若改变了,需要重置map        int count = word_num;//用于记录还需要考虑的字典里面元素的个数        for(int i=4; i<=string_length-word_length*word_num; i++)        {            //取出字符串            string SubString = s.substr(i, word_length);            int j = i;            while(my_Map.count(SubString)!=0 && my_Map[SubString]!=0 && (j+word_length)<=string_length)            {                my_Map[SubString] -= 1;                change_flag = 1;                count--;                                //考虑下一段字符串                j = j+word_length;                SubString = s.substr(j, word_length);                //若没有该substring,则break                //if(my_Map.count(SubString) == 0)                    //break;            }                        if(count == 0)                result.push_back(i);                        //重置map            if(change_flag == 1)            {                my_Map.clear();                InitialMap(my_Map, words);                change_flag = 0;                count = word_num;            }        }                return result;    }};



0 0
原创粉丝点击