【C++】 LeetCode 30. Substring with Concatenation of All Words
题目:
s:
words:
(order does not matter).
运行结果:
运行时间为33ms解析:
这道题意思是给定长字符串s,和一个字符串数组words,用words中的字符串组成s的一个子串,求解子串的起始位置,其中words中的字符串必须全部使用且只能使用一次,words中可以存在重复字符串,组合时不考虑words中字符串的顺序。思路:
这道题比较复杂。由于words中存在重复字符串,故采用map由于words中每个字符串为3个字符,则遍历的时候分为三组:0,3,6,9,12,15;1,4,7,10,13,16;2,5,8,11,14,17;对于每组分别遍历求解。 以第一组0,3,6,9,12,15为例,
代码:
class Solution {
public:vector findSubstring(string s, vector& words) {int lenWords=words.size();int lens=s.size();vector res;if(lenWords==0||lens==0)return res;int singlelen=words[0].size();int count=lenWords;map use;//初始化mapuse.clear();for(int i=0;ii?pre:i;while(pre+singlelen<=lens){str=s.substr(pre,singlelen);if(use.count(str)!=0&&use[str]!=0){use[str]--;count--;pre+=singlelen;if(count==0){res.push_back(i);break;}}else{break;}}if(use.count(s.substr(i,singlelen))!=0){use[s.substr(i,singlelen)]++;count++;} }}return res;}
}; 本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
