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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM