您的位置:首页 > 其它

leetcode 20. Valid Parentheses

2017-12-27 16:27 393 查看


题目

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.


解析

class Solution {
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
char[] ch = s.toCharArray();
int n = ch.length;
for (int i = 0; i < n; i++) {
char c = ch[i];
if (c == '{' || c == '[' || c == '(') stack.push(c);
else {
if (stack.size() == 0) return false;
char cc = stack.pop();
if (cc == '{' && c != '}') return false;
if (cc == '[' && c != ']') return false;
if (cc == '(' && c != ')') return false;
}
}
if (!stack.isEmpty()) return false;
return true;
}
}

public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: