您的位置:首页 > 其它

[LeetCode]20. Valid Parentheses

2016-09-22 15:26 387 查看
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.

解:栈的基本使用。

public class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<>();

char cur,top;

for (int i = 0;i < s.length();i++){

cur = s.charAt(i);

if (cur == '(' || cur == '[' || cur == '{'){
stack.push(String.valueOf(cur));
}else {
if (stack.empty()) return false;

top = stack.pop().charAt(0);

if (cur == ')' && top != '(')  return false;
if (cur == ']' && top != '[')  return false;
if (cur == '}' && top != '{')  return false;
}
}

if (!stack.empty()) return false;

return true;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode