Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
Example 1:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Example 2:
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Example 3:
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
Constraints:
m == s.length
n == t.length
1 <= m, n <= 105
s and t consist of uppercase and lowercase English letters.
t의 문자열에서 문자 개수를 모두 세어 s 문자열을 돌아가면서 세면 시간 복잡도가 O(m+n)으로 쉽게 나오는 문제라고 생각하였다.
문자열의 최소값을 찾기 위해 left 포인터와 right 포인터를 두어 문자를 모두 세었다면 left를 올리면서 가장 짧은 값을 확인하였다.
class Solution {
public String minWindow(String s, String t) {
int left = 0, right = 0;
int m = s.length();
int n = t.length();
if(m<n) return "";
int count = 0;
int[] arr = new int[52];
boolean[] arr2 = new boolean[52];
int result = Integer.MAX_VALUE;
String answer = "";
for(int i=0; i<n; i++){
char c = t.charAt(i);
if(Character.isUpperCase(c)){
arr[c-'A'+26]++;
arr2[c-'A'+26] = true;
} else{
arr[c-'a']++;
arr2[c-'a'] = true;
}
}
for(int i=0; i<m; i++){
char c = s.charAt(i);
int x = 0;
if(Character.isUpperCase(c)) x = c-'A'+26;
else x = c-'a';
if(arr2[x]){
arr[x]--;
if(arr[x]>=0) count++;
}
right++;
if(count==n){
while(left<right){
char c2 = s.charAt(left);
int x2 = 0;
if(Character.isUpperCase(c2)) x2 = c2-'A'+26;
else x2 = c2-'a';
left++;
if(arr2[x2]){
arr[x2]++;
if(arr[x2]>0){
count--;
break;
}
}
}
if(result>right-left+1){
result = right-left+1;
answer = s.substring(left-1, right);
}
}
}
return result == Integer.MAX_VALUE ? "" : answer;
}
}
다른 사람들의 풀이를 살펴보니 배열을 알파벳 개수인 52개가 아니라 알파벳의 유니코드 최대 값인 z 122 를 넘어선 128로 둔 다음 인덱스에 문자를 그대로 넣어 계산하는 편이 가독성도 좋고 속도도 빨랐을 것이다.