[LeetCode]30.Substring with Concatenation of All Words

160 篇文章 28 订阅
【题目】

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值