• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ying_vincent
博客园    首页    新随笔    联系   管理    订阅  订阅

LeetCode: Substring with Concatenation of All Words

自己想的大体思路还是对的,不过可以改进的很多,最后网上找了个勉勉强强过large的答案,用map实在太容易超时了。。

 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string S, vector<string> &L) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int len = L[0].size();
 7         int size = L.size();
 8         map<string, int> T;
 9         map<string, int> V;
10         for (int i = 0; i < L.size(); i++) T[L[i]]++;
11         vector<int> ret;
12         for (int i = 0; i < S.size()-size*len+1; i++) {
13             V.clear();
14             int j = 0;
15             for (; j < size; j++) {
16                 string tmp = S.substr(i+j*len, len);
17                 if (T.find(tmp) != T.end()) V[tmp]++;
18                 else break;
19                 if (V[tmp] > T[tmp]) break;
20             }
21             if (j == size) ret.push_back(i);
22         }
23         return ret;
24     }
25 };

 C#

 1 public class Solution {
 2     public List<int> FindSubstring(string s, string[] words) {
 3         int len = words[0].Length;
 4         int size = words.Length;
 5         Dictionary<string, int> T = new Dictionary<string, int>();
 6         Dictionary<string, int> V = new Dictionary<string, int>();
 7         for (int i = 0; i < size; i++) {
 8             if (T.ContainsKey(words[i])) T[words[i]]++;
 9             else T.Add(words[i], 1);
10         }
11         List<int> ans = new List<int>();
12         for (int i = 0; i < s.Length-size*len+1; i++) {
13             V.Clear();
14             int j = 0;
15             for (; j < size; j++) {
16                 string tmp = s.Substring(i+j*len, len);
17                 if (T.ContainsKey(tmp)) {
18                     if (V.ContainsKey(tmp)) V[tmp]++;
19                     else V.Add(tmp, 1);
20                 }
21                 else break;
22                 if (V[tmp] > T[tmp]) break;
23             }
24             if (j == size) ans.Add(i);
25         }
26         return ans;
27     }
28 }
View Code

 

posted @ 2013-04-21 14:55  ying_vincent  阅读(222)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3