程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode OJ Minimum Window Substring

LeetCode OJ Minimum Window Substring

編輯:C++入門知識

LeetCode OJ Minimum Window Substring


Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

 

char *minWindow(char *S, char *T) {
	int SL = strlen(S), TL = strlen(T);
	bool inT['z' + 1] = { false };
	int num['z' + 1] = { 0 };
	for (int i = 0; i < TL; i++) num[T[i]] += inT[T[i]] = true;
	int ps1 = 0, ps2 = -1, ansP = 0, ansL = SL + 1;
	while (ps2 < SL)
		if (!TL) {
			if (ansL > ps2 - ps1 + 1) ansL = ps2 + 1 - (ansP = ps1);
			if (inT[S[ps1]] && ++num[S[ps1]] > 0) TL++;
			ps1++;
		} else if (--num[S[++ps2]] >= 0 && inT[S[ps2]]) TL--;
	if ((S + ansP)[ansL]) (S + ansP)[ansL] = '\0';
	return ansL == SL + 1 ? "" : S + ansP;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved