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

Commit 6d07c92

Browse files
Create Longest Valid Parentheses
1 parent 685e18a commit 6d07c92

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
想法:用一個 stack 紀錄左括號的位置,當出現右括號時一定是與最右邊的左括號抵銷,也就是 stack 的頂部元素
2+
所以抵銷後的合法 substring 必然是從第二個元素到目前位置為子字串長度。
3+
只需注意如果 stack 抵銷後已經空了的話,代表從 s[startvalidindex ... i] 都是合法子字串
4+
startvalidindex 會因為 右括號多於左括號(代表不可能出現合法字串)而向後更動
5+
6+
Time Complexity : O(n) for traversing all elements
7+
Space Complexity : O(n) for the stack (which store all '(' elements)
8+
9+
class Solution {
10+
public:
11+
int longestValidParentheses(string s) {
12+
stack<int> leftindex ;
13+
int ans = 0 ;
14+
int startvalidindex = 0 ;
15+
16+
for(int i = 0 ; i < s.length() ; i++) {
17+
if ( s[i] == '(' )
18+
leftindex.push(i) ;
19+
else {
20+
// s[i] == ')'
21+
if ( leftindex.empty() ) {
22+
startvalidindex = i + 1 ;
23+
continue ;
24+
}
25+
26+
leftindex.pop() ;
27+
int startindex = (leftindex.empty())?
28+
startvalidindex -1 : leftindex.top() ;
29+
ans = max(ans , i - startindex) ;
30+
}
31+
}
32+
33+
return ans ;
34+
}
35+
};
36+
37+
// 法二:由於字串中只會出現 '(' 以及 ')',所以我們可以由左向右看過所有字串,當 '('數量等於 ')'時,合法子字串長度就是 '(' + ')' 的數量
38+
因此,我們只需紀錄出現的數量,並在 ')' 多於 '(' 時重設為 0 即可(出現該情況代表往前元素不會形成合法子字串)
39+
同時,我們也須由右向左看並執行相同程序,只需注意重設條件為 '(' 多於 ')'
40+
41+
Time Complexity : O(n) for traversing all elements
42+
Space Complexity : O(1) for variables
43+
44+
class Solution {
45+
public:
46+
int longestValidParentheses(string s) {
47+
int left = 0 , right = 0 ;
48+
int ans = 0;
49+
for(int i = 0 ; i < s.length() ; i++) {
50+
if (s[i] == ')')
51+
right++ ;
52+
else
53+
left++ ;
54+
55+
if ( right == left )
56+
ans = max(ans , right * 2) ;
57+
else if (right > left)
58+
left = right = 0 ;
59+
}
60+
left = right = 0 ;
61+
for(int i = s.length() - 1 ; i >= 0 ; i--) {
62+
if (s[i] == ')')
63+
right++ ;
64+
else
65+
left++ ;
66+
67+
if ( right == left )
68+
ans = max(ans , right * 2) ;
69+
else if (left > right)
70+
left = right = 0 ;
71+
}
72+
73+
74+
return ans ;
75+
}
76+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /