c/c++语言开发共享#leetcode刷题之路30-串联所有单词的子串

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。 示例 1:输入: s = "barfoothefoobarman …

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:
输入:
s = “barfoothefoobarman”,
words = [“foo”,”bar”]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 “barfoor” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = “wordgoodgoodgoodbestword”,
words = [“word”,”good”,”best”,”word”]
输出:[]

思路:首先为了方便比较,把原vector和用于存储的目标vector都要排序,排序后就可以知道两者是否完全相等了;剩下的就是暴力循环;

#include <iostream>  #include <vector>  #include <algorithm>  using namespace std;    vector<int> findsubstring(string s, vector<string>& words) {      sort(words.begin(),words.end());      vector<int> ans;      vector<string> temp;      int n=words.size();      if(n==0) return ans;      int len=words[0].length();      if(s.length()<n*len) return ans;      for(int i=0;i<s.length()-n*len+1;i++)      {          int t=i;          if(find(words.begin(),words.end(),s.substr(t,len))!=words.end())          {              temp.push_back(s.substr(t,len));              t=t+len;          }          for(int j=1;j<n;j++)          {              if(find(words.begin(),words.end(),s.substr(t,len))!=words.end())              {                  temp.push_back(s.substr(t,len));                  t=t+len;              }              else              {                  temp.clear();                  break;              }          }          sort(temp.begin(),temp.end());          if(temp==words) ans.push_back(i);          temp.clear();      }      return  ans;  }    int main() {      string s="aaa";      vector<string> a={"a","a"};      vector<int> ans=findsubstring(s,a);      std::cout << ans.size() << std::endl;      //std::cout << ans[0]<<ans[1] << std::endl;      return 0;  }

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/604744.html

(0)
上一篇 2021年5月12日
下一篇 2021年5月12日

精彩推荐