You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in wordsexactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9]
.
思路:如果 从某个位置 i 开始满足条件,那么一定是在[ i , i + 所有要找单词总字符长度 ) 区间中,且每个位置 i + 单个单词固定长度*k 都是某个要查找单词的开始位置。所以:
从字符串第 i 个字符开始,以 [ i , i + 所有要找单词总字符长度 ) 为区间查找每个单词是否存在,因为每个单词固定长度,所以查找的位置idx必须满足 (idx-i)% 单个单词长度 == 0
用 isFind 数组 来存储每个单词查找到与否的状态,每个单词的状态 存在 isFind的中的位置为 (idx-i)/ 单个单词长度
如果 isFind中 每个位置都是都找到了,那就符合条件。
错误的解法 :先排序,用lastIndex来记录是否有重复,但是只有 重复一次即连续两个单词一样的情况有效,当第三个也重复的时候找了第一个单词找的位置,而lastIndex记录的是第二次查找的位置 所以不可行
#include
#include
#include
#include
using namespace std;
class Solution {
public:
vector
findSubstring(string s, vector
& words) { vector
ret; int wordsSize=words.size(); if(wordsSize==0) return ret; int wordLenth = words[0].size(); if(wordLenth==0) return ret; int wordsCount=wordsSize*wordLenth; //cout<<"string:"<
<<" wordLenth:"<
<<" wordsSize:"<
<
isFind(wordsSize,0); // 记录上一个搜索的位置,用于去重,但是连续三个或者三个以上的重复,就有问题,第二个单词重复时lastIndex==id,再次搜索, // 然后lastIndex记录第二个搜索位置,第三个单词重复时, // 查到到第一单词的位置,而lastIndex记录的是第二次搜索的位置。。。所以不行!!!! int lastIndex=-1; for(;j
words; words.push_back("aa"); words.push_back("aa"); words.push_back("aa"); //words.push_back("wing"); //words.push_back("ding"); //words.push_back("wing"); //int idx= s.find("bar",1) ; //cout<
<
ret=sl.findSubstring(s,words); for(unsigned int i=0;i
正确
#include
#include
#include
#include
using namespace std;
class Solution {
public:
vector
findSubstring(string s, vector
& words) { vector
ret; int wordsSize=words.size(); if(wordsSize==0) return ret; int wordLenth = words[0].size(); if(wordLenth==0) return ret; int wordsCount=wordsSize*wordLenth; //cout<<"string:"<
<<" wordLenth:"<
<<" wordsSize:"<
<
isFind(wordsSize,0);//记录每个单词是否找到 //int lastIndex=-1;//记录上一个搜索的位置,用于去重,但是连续三个或者三个以上的重复,就有问题,第二个单词重复时lastIndex==id,再次搜索,lastIndex记录第二个搜索位置,第三个单词重复时,查到到第一单词的位置,而lastIndex记录的是第二次搜索的位置。。。所以不行!!!! for(;j
words; words.push_back("aa"); words.push_back("aa"); words.push_back("aa"); //words.push_back("wing"); //words.push_back("ding"); //words.push_back("wing"); //int idx= s.find("bar",1) ; //cout<
<
ret=sl.findSubstring(s,words); for(unsigned int i=0;i