#leetcode 30 - concatenate all word substrings

Keywords: C++ REST

Given a string s and some words of the same length. Find out the starting position of a substring in s that can be formed by concatenating all words in words.
Note that the substring should exactly match the words in the words, and there should be no other characters in the middle, but the sequence of words in the words should not be considered.

Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Interpretation:
The substrings starting with indexes 0 and 9 are "barfoor" and "foobar", respectively.
The order of output is not important, and [9,0] is also a valid answer.
Example 2:
Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []

Idea: first, in order to facilitate comparison, the original vector and the target vector used for storage should be sorted. After sorting, you can know whether they are completely equal; the rest is the violent cycle;

#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;
}

Posted by djcee on Sat, 07 Dec 2019 13:47:19 -0800