leetcode20. Valid Parentheses
来源:互联网 发布:windows api pdf 编辑:程序博客网 时间:2024/05/29 07:39
20. Valid Parentheses
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.
解法一
左半边的括号入栈,右半边的括号需要判断一下是否和栈顶的左半边匹配,如果不匹配,返回false。
tips
String.valueOf()将其他类型转为字符串。
s.toCharArray字符串转char数组。
Stack,泛型里面都是对象类型。字符对象Character和字符判断是否相等 c.equals(‘{‘)。注意是单引号。字符对象有equals方法。
字符比较:c == ‘{‘。
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if ("{([".contains(String.valueOf(c))) { stack.push(c); } else { if (!stack.empty() && is_valid(c, stack.peek())) { stack.pop(); } else { return false; } } } return stack.empty(); } private boolean is_valid(Character s, Character peek) { return (s.equals(')') && peek.equals('(')) || (s.equals('}') && peek.equals('{')) || (s.equals(']') && peek.equals('[')); } private static boolean is_valid2(char s, char peek) { return s == ')' && peek =='(' || s == '}' && peek == '{' || s == ']' && peek == '['; }}
解法二
输入’(‘,push’)’。输入’)’,判断栈顶元素是否是’)’。
public class Solution { 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(); }}
0 0
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- Leetcode20. Valid Parentheses
- leetcode20:Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 【LeetCode20】【Valid Parentheses】
- Leetcode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 深度学习 13. 能力提升, 一步一步的介绍如何自己构建网络和训练,利用MatConvNet(二),思路整理
- 连接oracle报错“ORA-28547:connection to server failed,probable Oracle Net admin 解决办法
- jQuery中的$(window).load()与$(document).ready()
- Python爬虫学习日记:模拟带有cookie的登陆
- 被JAVA架构师面试后的经验总结
- leetcode20. Valid Parentheses
- qq互联登录java版本
- Linux下使用Visual Studio Code
- activemq 使用?
- Android Studio出现Failed to open zip file问题的解决方法
- GameObject.instantiate 生成继承自其他的gameobject的问题
- dubbo报错
- 算法提高 7-1用宏求球的体积
- Android Studio 中使用 butterknife