《剑指offer》第三十题(串联所有单词的子串)

class Solution {
public:
    void find(string s,vector<string> words, vector<int>& res,
             int len_s,int len_words,int len_word)
    {
        vector<int> index;
        
        for(int i=0;i<len_s-len_word+1;i++)//对于每个字符,看是否是其中一个单词,是的话编码,不是的话取-1
        {
            bool flag=true;
            for(int j=0;j<len_words;j++)
            {
                int k=0;
                while(k<len_word && words[j][k]==s[i+k])
                    k++;
                if(k==len_word)
                {
                    index.push_back(j+1);
                    flag=false;
                    break;
                }
                    
            }
            if(flag)
                index.push_back(-1);
        }
        
        int length=index.size();
        int sum=0;//设立两个标准,一个是编码的和,一个是编码之间的异或,注意重复单词以第一个为准
        int chengji=0;
        for(int i=0;i<len_words;i++)
        {
            bool is_flag=false;
            for(int j=0;j<i;j++)
            {
                if(words[j]==words[i])
                {
                    sum+=j+1;
                    chengji= chengji ^ (j+1);
                    is_flag=true;
                    break;
                }
            }
            if(!is_flag)
            {
                sum+=i+1;
                chengji=chengji ^ (i+1);
            }
                
        }
        
        for(int i=0;i<length;i++)//对编码序列进行检测,满足上述两个标准的即可
        {
            int temp=i;
            int cur_sum=0;
            int cur_chengji=0;
            int j=0;
            while((temp+j*len_word<length) && j<len_words)
            {
                cur_sum+=index[temp+j*len_word];
                cur_chengji=cur_chengji ^ (index[temp+j*len_word]);
                j++;
            }
                
            if(cur_sum==sum&&cur_chengji==chengji&&j==len_words)
                res.push_back(temp);
        }
    }
    
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        int len_s=s.size();//把边界条件判断一遍
        int len_words=words.size();

        if(len_words==0 || len_s==0)
            return res;

        int len_word=words[0].size();
        if(len_s<len_word)
            return res;
        
        find(s,words,res,len_s,len_words,len_word);//进行查找
        
        return res;
    }
};

 分析:

好恶心。

猜你喜欢

转载自www.cnblogs.com/CJT-blog/p/10804666.html