File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 문제 설명
3+ * - 주어진 문자열 s에서 주어진 문자열 t의 모든 문자를 포함하는 최소 윈도우를 찾는 문제
4+ *
5+ * 아이디어
6+ * - 슬라이딩 윈도우 + 해시맵(need, window)을 이용하여 풀이한다.
7+ * - 오른쪽 포인터를 먼저 이동하고, 이미 모두 포함되어 있는 경우 왼쪽 포인터를 이동하여 최소 윈도우를 찾는다.
8+ *
9+ */
10+ function minWindow ( s : string , t : string ) : string {
11+ if ( t . length > s . length ) return "" ;
12+
13+ const need = new Map < string , number > ( ) ;
14+ const window = new Map < string , number > ( ) ;
15+
16+ for ( const char of t ) {
17+ need . set ( char , ( need . get ( char ) || 0 ) + 1 ) ;
18+ }
19+
20+ let have = 0 ;
21+ let needSize = need . size ;
22+ let res = [ - 1 , - 1 ] ;
23+ let resLen = Infinity ;
24+
25+ let left = 0 ;
26+
27+ for ( let right = 0 ; right < s . length ; right ++ ) {
28+ const c = s [ right ] ;
29+ window . set ( c , ( window . get ( c ) || 0 ) + 1 ) ;
30+
31+ if ( need . has ( c ) && window . get ( c ) === need . get ( c ) ) {
32+ have ++ ;
33+ }
34+
35+ while ( have === needSize ) {
36+ const currentResLen = right - left + 1 ;
37+ if ( currentResLen < resLen ) {
38+ res = [ left , right ] ;
39+ resLen = currentResLen ;
40+ }
41+
42+ const lChar = s [ left ] ;
43+ window . set ( lChar , window . get ( lChar ) ! - 1 ) ;
44+
45+ if ( need . has ( lChar ) && window . get ( lChar ) ! < need . get ( lChar ) ! ) {
46+ have -- ;
47+ }
48+ left ++ ;
49+ }
50+ }
51+
52+ const [ start , end ] = res ;
53+ return resLen === Infinity ? "" : s . slice ( start , end + 1 ) ;
54+ }
You can’t perform that action at this time.
0 commit comments