0
点赞
收藏
分享

微信扫一扫

20. Valid Parentheses

梦为马 2022-08-03 阅读 28


Given a string containing just the characters’(’,’)’,’{’,’}’,’[‘and’]’, determine if the input string is valid.
The brackets must close in the correct order,"()“and”()[]{}“are all valid but”(]“and”([)]"are not.

import java.util.Stack;

public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
//使用foreach循环
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}

Java2

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{')
stack.push(c);
else {
if (stack.isEmpty())
return false;
if (c == ')') {
if ('(' != stack.pop())
return false;
} else if (c == ']') {
if ('[' != stack.pop())
return false;
} else if (c == '}') {
if ('{' != stack.pop())
return false;
}
}
}
return stack.isEmpty();
}
}


举报

相关推荐

0 条评论