20. Valid Parentheses (Easy)
来源:互联网 发布:广州恒大淘宝队微博 编辑:程序博客网 时间:2024/06/06 00:41
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.
括号匹配,用到了数据结构中的栈,这里用Java完成代码:
Solution:
Java:
import java.util.Stack;public class Solution { public boolean match(char c1, char c2) { if(c1 == '(' && c2 == ')' || c1 == ')' && c2 == '(') { return true; } if(c1 == '{' && c2 == '}' || c1 == '}' && c2 == '{') { return true; } if(c1 == '[' && c2 == ']' || c1 == ']' && c2 == '[') { return true; } return false; } public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c == '(' || c == '{' || c == '[') { stack.push(c); } else { if(stack.isEmpty()) return false; // 字符串开始就是右括号 char cc = stack.pop(); if(!match(c, cc)) { return false; } } } return stack.isEmpty(); } public void test() { System.out.println(isValid("]")); } public static void main(String[] args) { new Solution().test(); }}
0 0
- 20. Valid Parentheses (Easy)
- 20. Valid Parentheses [easy] (Python)
- 20.Valid Parentheses(Stack-Easy)
- Easy-题目47:20. Valid Parentheses
- Leetcode 20. Valid Parentheses (Easy) (cpp)
- 【leetcode】Valid Parentheses(easy)
- Valid Parentheses (EASY)
- [Leetcode 20, Easy] Valid Parentheses
- 【Leetcode-Easy-20】 Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- LeetCode-Easy部分中标签为String 20. Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- LeetCode-20-Valid Parentheses(堆栈)-Easy
- Easy 5 Valid Parentheses(20)
- LeetCode OJ 20 Valid Parentheses [Easy]
- LeetCode-Easy刷题(5) Valid Parentheses
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- mac 原始hosts
- LL160IntersectionOfTwoLinkedLists
- 不要让自己成为温水里的青蛙
- 深度卷积神经网络在目标检测中发展
- CSS里面position:relative与position:absolute 区别
- 20. Valid Parentheses (Easy)
- POJ1251 JungleRoads 最小生成树
- Git客户端下载及安装
- 117. Populating Next Right Pointers in Each Node II
- 聊天机器人--基础版本
- 四:Struts拦截器简单介绍
- 【codevs 1029】遍历问题
- 叙事——2016/11/13
- Android ListView与RecyclerView对比浅析--缓存机制--转自腾讯Bugly 作者 Bugly_Tony