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

Commitb26c1e6

Browse files
author
applewjg
committed
add solution
Change-Id: Icc6c68e02f24d86c11e8e319326bd00cb10056c0
1 parent29fcdd2 commitb26c1e6

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

‎LongestValidParentheses.java

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
Author:King, wangjingui@outlook.com
2+
Author:Andy, nkuwjg@gmail.com
33
Date: Dec 20, 2014
44
Problem: Longest Valid Parentheses
55
Difficulty: Easy
@@ -31,7 +31,7 @@ public int longestValidParentheses_1(String s) {
3131
}
3232
returnres *2;
3333
}
34-
publicintlongestValidParentheses(Strings) {
34+
publicintlongestValidParentheses_2(Strings) {
3535
intn =s.length();
3636
if (n <=1)return0;
3737
intres =0;
@@ -46,4 +46,30 @@ public int longestValidParentheses(String s) {
4646
}
4747
returnres;
4848
}
49-
}
49+
publicintlongestValidParentheses(Strings) {
50+
intcounter =0,val =0,res =0;
51+
for (inti =0;i <s.length(); ++i) {
52+
counter +=s.charAt(i) =='(' ?1 : -1;
53+
if (counter <0) {
54+
val =counter =0;
55+
continue;
56+
}
57+
val +=s.charAt(i) =='(' ?0 :2;
58+
res =counter ==0 ?Math.max(res,val) :res;
59+
}
60+
val =counter =0;
61+
for (inti =s.length() -1;i >=0; --i) {
62+
counter +=s.charAt(i) ==')' ?1 : -1;
63+
if (counter <0) {
64+
val =counter =0;
65+
continue;
66+
}
67+
val +=s.charAt(i) ==')' ?0 :2;
68+
res =counter ==0 ?Math.max(res,val) :res;
69+
}
70+
returnres;
71+
}
72+
}
73+
74+
75+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp