30. Substring with Concatenation of All Words

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值