leetcode题库——与所有单词相关联的字串

版权声明: https://blog.csdn.net/Dorothy_Xue/article/details/84304379

题目描述:

给定一个字符串 和一些长度相同的单词 words。 s 中找出可以恰好串联 words 中所有单词的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

输入:
  s = "barfoothefoobarman",
  words = ["foo","bar"]
输出: [0,9]
解释: 从索引 0 和 9 开始的子串分别是 "barfoor" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

示例 2:

输入:
  s = "wordgoodstudentgoodword",
  words = ["word","student"]
输出: []

 方法:

class Solution {
public:
    vector<int> res;
    int length;
    int flag=0;
    
    vector<int> findSubstring(string s, vector<string>& words) {
        if(s.size()==0||words.size()==0)return res;
        length=words.size();
        vector<int> a(length,0);
        for(int i=0;i<length;i++)flag+=words[i].size();
        for(int i=0;i<s.size()-flag+1;i++){
            string str=s.substr(i,flag);
            if(check(words,a,str))res.push_back(i);
        }
        return res;
    }
    
    bool check(vector<string>& words,vector<int> a,string str){
        int i=0;
        while(i<str.size()){
            int k=0;
            for(int j=0;j<length;j++){
                if(str.substr(i,words[j].size())==words[j]&&a[j]==0){
                    k=1;
                    a[j]=1;
                    i=i+words[j].size();
                    if(i==str.size())return true;
                    break;
                }
            }
            if(k==0)return false;
        }
    }
};

思路:

从给定字符串中,依次用与words中字符总数相同长度的子串,与words进行比较。

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/84304379
今日推荐