首页 > 代码库 > [LeetCode]30.Substring with Concatenation of All Words

[LeetCode]30.Substring with Concatenation of All Words

【题目】

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).

【分析】

先用map<string,int>统计L中每个单词的个数(L中单词可能会重复)。

从第一个字符开始遍历,对于第i个字符,由它开始和L中单词匹配,如果不匹配,跳到第i+1字符继续匹配。

【代码】

/*********************************
*   日期:2015-01-25
*   作者:SJF0115
*   题目: 30.Substring with Concatenation of All Words
*   网址:https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        int strLen = S.length();
        int size = L.size();
        int wordLen = (L[0]).length();
        vector<int> result;
        if(strLen <= 0 || size <= 0){
            return result;
        }//if
        map<string,int> words;
        // word count
        for(int i = 0;i < size;++i){
            ++words[L[i]];
        }//for
        map<string,int> curMap = words;
        // 遍历寻找
        for(int i = 0;i <= strLen - size*wordLen;++i){
            curMap = words;
            // 从位置i寻找words
            for(int j = 0;j < size;++j){
                string substr = S.substr(i+j*wordLen,wordLen);
                // 不匹配
                if(words.find(substr) == words.end()){
                    break;
                }//if
                --curMap[substr];
                if(curMap[substr] < 0){
                    break;
                }//if
                // 一个匹配项
                if(j == size-1){
                    result.push_back(i);
                }//if
            }//for
        }//for
        return result;
    }
};

int main(){
    Solution solution;
    string s("barfoothefoobarman");
    vector<string> vec;
    vec.push_back("foo");
    vec.push_back("bar");
    vector<int> result = solution.findSubstring(s,vec);
    // 输出
    for(int i = 0;i < result.size();++i){
       cout<<result[i]<<endl;
    }//for
    return 0;
}


技术分享

[LeetCode]30.Substring with Concatenation of All Words