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 }