首页 > 代码库 > Leetcode: Substring with Concatenation of All Words
Leetcode: Substring with Concatenation of All Words
Description:
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).
分析: 这道题目告诉我们一定要认真读题目! 题目做了限制,会使得解题容易的多: 单词表中的words长度一样!
这样题目只要建立了哈希表,即可使用循环解决。 注意中间也有一些简单的trick,比如长度限制扫描范围等。
1 class Solution { 2 public: 3 vector<int> findSubstring(string S, vector<string> &L) { 4 vector<int> result; 5 int nums = L.size(); 6 if(nums==0) return result; 7 int wordsz = L[0].size(); 8 if(S.size()<(wordsz*nums)) return result; 9 10 unordered_map<string,int> dict,backup;11 string target;12 for(int i=0;i<nums;i++)13 dict[L[i]]++;14 backup =dict;15 16 for(int i=0;i<=S.size()-(wordsz*nums);i++)17 {18 int hitnum = 0;19 for(int j =i;j!=i+wordsz*nums;j+=wordsz)20 {21 target.assign(S.begin()+j,S.begin()+j+wordsz);22 auto p = dict.find(target);23 if(p!=dict.end() && p->second)24 {25 hitnum++;26 p->second--;27 }28 else{29 dict = backup;30 break;31 }32 if(hitnum == nums)33 {34 dict = backup;35 result.push_back(i);36 break;37 }38 }39 40 }41 return result;42 }43 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。