首页 > 代码库 > [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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。