leetcode: Substring with Concatenation of All Words

http://oj.leetcode.com/problems/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).

思路

L里每个单词长度一样,写循环就方便了很多。先初始化一个map,统计L里每个单词出现的次数。每次循环如果某个单词没出现或者超出L中出现的错误就中断。

 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string S, vector<string> &L) {
 4         int l_size = L.size();
 5         
 6         if (l_size <= 0) {
 7             return vector<int>();
 8         }
 9         
10         vector<int> result;
11         map<string, int> word_count;
12         int word_size = L[0].size();
13         int i, j;
14         
15         for (i = 0; i < l_size; ++i) {
16             ++word_count[L[i]];
17         }
18         
19         map<string, int> counting;
20         
21         for (i = 0; i <= (int)S.length() - (l_size * word_size); ++i) {
22             counting.clear();
23             
24             for (j = 0; j < l_size; ++j) {
25                 string word = S.substr(i + j * word_size, word_size);
26                 
27                 if (word_count.find(word) != word_count.end()) {
28                     ++counting[word];
29                     
30                     if (counting[word] > word_count[word]) {
31                         break;
32                     }
33                 }
34                 else {
35                     break;
36                 }
37             }
38             
39             if (j == l_size) {
40                 result.push_back(i);
41             }
42         }
43         
44         return result;
45     }
46 };

 

posted @ 2013-10-30 17:53  移山测试工作室黑灯老师  阅读(6524)  评论(2编辑  收藏  举报
count website visits
Buy Computers