Given a string containing just the characters '(' and ')',
find the length of the longest valid (well-formed) parentheses substring.
For "(()",
the longest valid parentheses substring is "()",
which has length = 2.
Another example is ")()())",
where the longest valid parentheses substring is "()()",
which has length = 4.
public class Solution {
public static void main(String[] args) {
System.out.println( longestValidParentheses("()"));
}
public static int longestValidParentheses(String str) {
if (str == null || str.length() == 0) return 0;
int max = 0;
int total = 0;
int numberofLeftParentheses = 0;
for (int k = 0; k < str.length(); k++) {
if (str.charAt(k) == '(') {
numberofLeftParentheses++;
total++;
} else {
numberofLeftParentheses--;
total++;
}
if (numberofLeftParentheses == 0 && max < total) {
max = total;
}
if (numberofLeftParentheses < 0) {
total = 0;
numberofLeftParentheses = 0;
}
}
total = 0;
numberofLeftParentheses = 0;
for (int k = str.length() - 1; k >= 0; k--) {
if (str.charAt(k) == ')') {
numberofLeftParentheses++;
total++;
} else {
numberofLeftParentheses--;
total++;
}
if (numberofLeftParentheses == 0 && max < total) {
max = total;
}
if (numberofLeftParentheses < 0) {
total = 0;
numberofLeftParentheses = 0;
}
}
return max;
}
// this method will return total number of valid pare of parentheses (not continuous).
public static int totalValidPairOfParentheses(String str) {
if (str == null || str.length() == 0) return 0;
int total = 0;
int numberofLeftParentheses = 0;
for (int k = 0; k < str.length(); k++) {
if (str.charAt(k) == '(') {
numberofLeftParentheses++;
} else {
if (numberofLeftParentheses > 0) {
numberofLeftParentheses--;
total++;
}
}
}
return total;
}
}
本文介绍了一种求解字符串中最长有效括号子串长度的方法。通过两次遍历,分别从左到右和从右到左计算有效的括号对数,找出最长的有效括号子串长度。
384

被折叠的 条评论
为什么被折叠?



