首页 > 代码库 > 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 };