You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
思路:很淳朴的思路,依据最基本的想法进行查找
虽说循环是三层循环,但最多是平方级别的复杂度
#include <iostream> #include <string> #include <vector> using namespace std; /* You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). */ void Concatenation(vector<string>& vec,string& s,vector<int>& indices) { int num = vec.size(); // 匹配数组的数目 int len = s.size(); // 字符串的长度 int sublen = vec[0].size(); //每一个被匹配的字符串的长度 vector<int> flag(vec.size(),0); int count; int i,j,k; for(i=0;i<len-num*sublen;i++) { count = 0; flag.assign(flag.size(),0); for(j=i;j<len;j++) { for(k=0;k<num;k++) if(count < num && !s.compare(j,sublen,vec[k])) { if(flag[k] == 1) { i = j-1; j = len; break; } else { flag[k] =1; count++; if(count == num) { indices.push_back(j-(num-1)*sublen); i = j-1; j = len; } j+=sublen-1; break; } } } } } int main() { string s("sbarfoothefoobarman"); string s1("foo"); string s2("bar"); vector<string> vec; vec.push_back(s1); vec.push_back(s2); vector<int> indices; Concatenation(vec,s,indices); for(int i=0;i<indices.size();i++) cout<<indices[i]<<endl; return 0; }
Substring with Concatenation of All Words--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44751809