Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5f0942a

Browse files
author
applewjg
committed
MinimumWindowSubstring
Change-Id: I8b29b804c6e2e57e9f767f31fe1c433604b609f5
1 parentbda93ff commit5f0942a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎MinimumWindowSubstring.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 25, 2014
4+
Problem: Minimum Window Substring
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/minimum-window-substring/
7+
Notes:
8+
Given a string S and a string T, find the minimum window in S which will contain all the
9+
characters in T in complexity O(n).
10+
For example,
11+
S = "ADOBECODEBANC"
12+
T = "ABC"
13+
Minimum window is "BANC".
14+
Note:
15+
If there is no such window in S that covers all characters in T, return the empty string "".
16+
If there are multiple such windows, you are guaranteed that there will always be only one unique
17+
minimum window in S.
18+
19+
Solution: 1. Use two pointers: start and end.
20+
First, move 'end'. After finding all the needed characters, move 'start'.
21+
2. Use array as hashtable.
22+
*/
23+
24+
publicclassSolution {
25+
publicStringminWindow(StringS,StringT) {
26+
intN =S.length(),M =T.length();
27+
if (N <M)returnnewString("");
28+
int[]need =newint[256];
29+
int[]find =newint[256];
30+
for (inti =0;i <M; ++i)
31+
need[T.charAt(i)]++;
32+
33+
intcount =0,resStart = -1,resEnd =N;
34+
for (intstart =0,end =0;end <N; ++end)
35+
{
36+
if (need[S.charAt(end)] ==0)
37+
continue;
38+
if (find[S.charAt(end)] <need[S.charAt(end)])
39+
count++;
40+
find[S.charAt(end)]++;
41+
if (count !=M)continue;
42+
// move 'start'
43+
for (;start <end; ++start) {
44+
if (need[S.charAt(start)] ==0)continue;
45+
if (find[S.charAt(start)] <=need[S.charAt(start)])break;
46+
find[S.charAt(start)]--;
47+
}
48+
// update result
49+
if (end -start <resEnd -resStart) {
50+
resStart =start;
51+
resEnd =end;
52+
}
53+
}
54+
return (resStart == -1) ?newString("") :S.substring(resStart,resEnd +1);
55+
}
56+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp