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

Commitb4f77c2

Browse files
author
applewjg
committed
LongestValidParentheses
Change-Id: I4f04cf277e6b91fb7e3dbb377f824237fb96b26c
1 parent8fd268f commitb4f77c2

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎LongestValidParentheses.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Longest Valid Parentheses
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/longest-valid-parentheses/
7+
Notes:
8+
Given a string containing just the characters '(' and ')', find the length of the longest valid
9+
(well-formed) parentheses substring.
10+
For "(()", the longest valid parentheses substring is "()", which has length = 2.
11+
Another example is ")()())", where the longest valid parentheses substring is "()()",
12+
which has length = 4.
13+
14+
Solution: O(n).
15+
*/
16+
17+
publicclassSolution {
18+
publicintlongestValidParentheses_1(Strings) {
19+
Stack<Integer>stk =newStack<Integer>();
20+
intres =0,count =0;
21+
for(inti =0;i <s.length(); ++i) {
22+
if (s.charAt(i) =='(') {
23+
stk.push(count);
24+
count =0;
25+
}elseif (stk.empty() ==false) {
26+
count += (1 +stk.pop());
27+
res =Math.max(res,count);
28+
}else {
29+
count =0;
30+
}
31+
}
32+
returnres *2;
33+
}
34+
publicintlongestValidParentheses(Strings) {
35+
intn =s.length();
36+
if (n <=1)return0;
37+
intres =0;
38+
int[]f =newint[n];
39+
for(inti=n-2;i>=0;i--){
40+
intmatch =i +f[i+1] +1;
41+
if(match<n&&s.charAt(i)=='('&&s.charAt(match)==')'){
42+
f[i]=f[i+1]+2;
43+
if(match+1<n)f[i]+=f[match+1];
44+
}
45+
res =Math.max(res,f[i]);
46+
}
47+
returnres;
48+
}
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp