首页 > 其他 > 详细

[Leetcode] Substring with Concatenation of All Words

时间:2014-04-12 14:50:11      阅读:340      评论:0      收藏:0      [点我收藏+]

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].

老是超时,终于过了。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string S, vector<string> &L) {
 4         vector<int> res;
 5         if (L.size() < 1) return res;
 6         
 7         int Len = L.size() * L[0].length();
 8         int len = L[0].length();
 9         if (S.length() < Len) return res;
10         
11         map<string, int> word_count;
12         for (int i = 0; i < L.size(); ++i) {
13             word_count[L[i]]++;
14         }
15         map<string, int> word_detect;
16         for (int i = 0; i <= S.length() - Len; ++i) {
17             word_detect.clear();
18             string substr;
19             int j = 0;
20             for (j = 0; j < Len; j += len) {
21                 substr = S.substr(i + j, len);
22                 if (word_count.find(substr) == word_count.end())
23                     break;
24                 ++word_detect[substr];
25                 if (word_detect[substr] > word_count[substr])
26                     break;
27             }
28             if (j==Len) res.push_back(i);
29         }
30         return res;
31     }
32 };
bubuko.com,布布扣

 

[Leetcode] Substring with Concatenation of All Words,布布扣,bubuko.com

[Leetcode] Substring with Concatenation of All Words

原文:http://www.cnblogs.com/easonliu/p/3659078.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!