Substring with Concatenation of All Words 字符串操作 匹配的字串数

来源:互联网 发布:python beginwith 编辑:程序博客网 时间:2024/05/22 08:11

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

class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {                       int wordLen=words.size();        vector<int> res;                if(wordLen<=0)            return res;            int wordSize=words[0].size();                int i,j;        map<string,int> wordCount;        //map统计每个单词出现        for(i=0;i<wordLen;i++)            wordCount[words[i]]++;                map<string,int> tmp;        int len=s.length();       // for(i=0;i<=s.length()-(wordLen*wordSize);i++) 刚开始s.length没有用int转换一直过不了       //改为i<=(int)s.length() 过了        for(i=0;i<=len-(wordLen*wordSize);i++)        {            tmp.clear();            for(j=0;j<wordLen;j++)            {               string str=s.substr(i+j*wordSize,wordSize);               if(wordCount.find(str)!=wordCount.end())               {                   tmp[str]++;                   if(tmp[str]>wordCount[str])                        break;               }               else                    break;            }            if(j==wordLen)                res.push_back(i);        }        return res;    }};

0 0