Skip to content

Commit b7d3488

Browse files
committed
O(n)时间里遍历,用空间换时间,遍历过程中记录信息,利用信息进行处理,额外的记录信息!
1 parent a0be99f commit b7d3488

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

string/Minimum Window Substring

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
2+
class Solution {
3+
public:
4+
string minWindow(string S, string T) {
5+
int lens = S.size(),lent = T.size();
6+
int srcT[128]; // 很多都采用256,其实ascii 码有效位数是7位,所以不必开那么大
7+
int srcS[128];
8+
fill(srcT,srcT + 128,0); // fill 与memset的使用,感觉fill更强大,memset要计算空间大小
9+
fill(srcS,srcS + 128,0);
10+
int foundS[128];
11+
int foundLen = 0;
12+
int start = 0,end = lens;
13+
int tstart = 0,tend = 0;
14+
for(int i = 0;i < lent;i++)
15+
srcT[T[i]] ++;
16+
for(int i = 0;i < lens;i++)
17+
{
18+
if(srcT[S[i]] != 0)
19+
{
20+
srcS[S[i]]++;
21+
if(srcS[S[i]] <= srcT[S[i]]) foundLen++;
22+
if(foundLen == lent)
23+
{
24+
tend = i;
25+
while(srcT[S[tstart]] == 0 || srcS[S[tstart]] > srcT[S[tstart]]) // start 要往后缩减的过程,比较重要,可优化
26+
{
27+
28+
if(srcT[S[tstart]] != 0)
29+
srcS[S[tstart]]--;
30+
tstart ++;
31+
}
32+
if(end - start > tend - tstart )
33+
{
34+
end = tend;
35+
start = tstart;
36+
}
37+
srcS[S[tstart]]--;
38+
foundLen--;
39+
tstart ++;
40+
}
41+
}
42+
}
43+
if(end == lens)
44+
return "";
45+
else
46+
return S.substr(start,end - start + 1);
47+
48+
}
49+
};
50+
51+
52+
53+
54+
55+
class Solution {
56+
public:
57+
string minWindow(string S, string T) {
58+
int lens = S.size(),lent = T.size();
59+
int srcT[128];
60+
int srcS[128];
61+
fill(srcT,srcT + 128,0);
62+
fill(srcS,srcS + 128,0);
63+
queue<int> index;
64+
int foundS[128];
65+
int foundLen = 0;
66+
int start = 0,end = lens;
67+
int tstart = 0,tend = 0;
68+
for(int i = 0;i < lent;i++)
69+
srcT[T[i]] ++;
70+
for(int i = 0;i < lens;i++)
71+
{
72+
if(srcT[S[i]] != 0)
73+
{
74+
index.push(i);
75+
srcS[S[i]]++;
76+
if(srcS[S[i]] <= srcT[S[i]]) foundLen++;
77+
if(foundLen == lent)
78+
{
79+
tend = i;
80+
tstart = index.front();
81+
while(srcS[S[tstart]]>srcT[S[tstart]]) // 建立了一个队列,每次都只从有效的字母开始。时间缩减了三分之一。
82+
{
83+
index.pop();
84+
srcS[S[tstart]]--;
85+
tstart = index.front();
86+
}
87+
if(end - start > tend - tstart )
88+
{
89+
end = tend;
90+
start = tstart;
91+
}
92+
srcS[S[tstart]]--;
93+
foundLen--;
94+
index.pop(); // 与srcS要保持一致
95+
}
96+
}
97+
}
98+
if(end == lens)
99+
return "";
100+
else
101+
return S.substr(start,end - start + 1);
102+
103+
}
104+
};

0 commit comments

Comments
 (0)