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

LeetCode: Minimum Window Substring

自己写的large没过,用了map,然后用了很多erase, iterator的,懂得一个道理,map这玩意比较慢,尽量少用,在用网上答案的时候没有给数组初始化为0就过不了

 1 class Solution {
 2 public:
 3     string minWindow(string S, string T) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int tag[256] = {0};
 7         int mark[256] = {0};
 8         int chars, count, head, beg;
 9         chars = count = head = 0;
10         beg = -1;
11         int min_w = INT_MAX;
12         for (int i = 0; i < T.size(); i++) {
13             if (!tag[T[i]]) chars++;
14             tag[T[i]]++;
15         }
16         for (int i = 0; i < S.size(); i++) {
17             if (!tag[S[i]]) continue;
18             mark[S[i]]++;
19             if (mark[S[i]] == tag[S[i]]) count++;
20             if (chars == count) {
21                 while (!tag[S[head]] || mark[S[head]] > tag[S[head]]) {
22                     mark[S[head]]--;
23                     head++;
24                 }
25                 if (i-head < min_w) {
26                     min_w = i-head;
27                     beg = head;
28                 }
29             }
30         }
31         if (beg == -1) return "";
32         else return S.substr(beg, min_w+1);
33     }
34 };

 C#

 1 public class Solution {
 2     public string MinWindow(string s, string t) {
 3         int[] tag = new int[256];
 4         int[] mark = new int[256];
 5         int chars = 0, count = 0, head = 0, beg = -1;
 6         int min_w = Int32.MaxValue;
 7         for (int i = 0; i < t.Length; i++) {
 8             if (tag[t[i]] == 0) chars++;
 9             tag[t[i]]++;
10         }
11         for (int i = 0; i < s.Length; i++) {
12             if (tag[s[i]] == 0) continue;
13             mark[s[i]]++;
14             if (mark[s[i]] == tag[s[i]]) count++;
15             if (chars == count) {
16                 while (tag[s[head]] == 0 || mark[s[head]] > tag[s[head]]) {
17                     mark[s[head]]--;
18                     head++;
19                 }
20                 if (i - head < min_w) {
21                     min_w = i - head;
22                     beg = head;
23                 }
24             }
25         }
26         if (beg == -1) return "";
27         else return s.Substring(beg, min_w + 1);
28     }
29 }
View Code

 

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