您的位置:首页 > 其它

Valid Parentheses & Longest Valid Parentheses

2016-07-13 11:03 253 查看
Valid Parentheses

Given a string containing just the characters
'(', ')'
,
'{'
,
'}'
,
'['
and
']'
, determine if the input string is valid.

Example

The brackets must close in the correct order,
"()"
and
"()[]{}"
are all valid but
"(]"
and
"([)]"
are not.

分析:

使用stack来保存每个括号,如果最上面的和当前括号匹配,则除去最上面的括号,否则把新括号加入。如果最后stack为空,则所有括号匹配。

public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
if (s == null || s.length() % 2 == 1) return false;
Stack<Character> stack = new Stack<Character>();

for (int i = 0; i < s.length(); i++) {
if (stack.size() == 0) {
stack.push(s.charAt(i));
} else {
char c1 = stack.peek();
char c2 = s.charAt(i);
if (c1 == '(' && c2 == ')' || c1 == '[' && c2 == ']' || c1 == '{' && c2 == '}') {
stack.pop();
} else {
stack.push(s.charAt(i));
}
}
}
return stack.isEmpty();
}
}


Longest Valid Parentheses

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 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++;
} 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++;
} else {
numberofLeftParentheses--;
}
total++;

if (numberofLeftParentheses == 0 && max < total) {
max = total;
}

if (numberofLeftParentheses < 0) {
total = 0;
numberofLeftParentheses = 0;
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: