LeetCode解题报告--Valid Parentheses
来源:互联网 发布:python 2.7 3.5 区别 编辑:程序博客网 时间:2024/06/09 18:57
**题目:**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.
分析:题意要求判断输入的符号(”()”,”{}”,”[]”)字符串是否是成对匹配。
改题用栈(stack)是最简单直接的解法,直接调用java内部stack类包。
1)新建一个栈,将输入的字符串中的“(”,“{”,“[”压入栈,
2)当遇到字符串中”)”或”}”或”]”,与栈最后一个元素进行判断,如如果当前的字符是”)”,则需要判断此时的栈顶元素是否为”)”,如果不是则直接返回false,结束程序;如果是则将栈顶元素pop,
3)循环执行2)中步骤,直至字符串遍历完成。
Java Accepted代码:
public class Solution { public boolean isValid(String s) { if (s.length() % 2 != 0) { return false; } Stack<Character> string = new Stack<Character>(); char ch; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '[' || s.charAt(i) == '(' || s.charAt(i) == '{') { string.push(s.charAt(i)); //System.out.println(string); } else { if (string.isEmpty()){ return false; } else { ch = s.charAt(i); switch (ch) { case ']': if (string.pop() != '[') return false; break; case ')': if (string.pop() != '(') return false; break; case '}': if (string.pop() != '{') return false; break; } } } } if(string.isEmpty()){ return true; }else{ return false; } }}
与此相关的内容在之前的博客《基于链表实现Java 自定义Stack栈》
相关代码放在个人github:https://github.com/gannyee/LeetCode/
0 0
- LeetCode解题报告--Valid Parentheses
- [LeetCode] Valid Parentheses 解题报告
- [LeetCode] Valid Parentheses 解题报告
- 【LeetCode】Valid Parentheses 解题报告
- Leetcode Valid Parentheses 解题报告
- [LeetCode]Longest Valid Parentheses, 解题报告
- LeetCode Longest Valid Parentheses 解题报告
- [LeetCode] Longest Valid Parentheses 解题报告
- 【LeetCode】Longest Valid Parentheses 解题报告
- [leetcode] 20. Valid Parentheses 解题报告
- [leetcode] 32. Longest Valid Parentheses 解题报告
- [Leetcode] 20. Valid Parentheses 解题报告
- [Leetcode] 32. Longest Valid Parentheses 解题报告
- leetcode解题报告20. Valid Parentheses
- Leetcode 32 Longest Valid Parentheses 解题报告。
- [leetcode javascript解题]Valid Parentheses
- LeetCode解题-#20-Valid Parentheses
- Valid Parentheses——解题报告
- struts2 异常处理 404错误
- html标签大全
- 为什么NOLOCK反而返回更少的数据
- 轻松实现文档转换的word转pdf转换器
- UITextView如何设置提示性文字
- LeetCode解题报告--Valid Parentheses
- JS table表格间线重叠的问题
- html <label>标签
- [原]opencv图像裁剪
- Ubuntu Server 命令
- String和StringBuffer详解
- codeforces 573C. Bear and Drawing
- dataguard备库连接sys用户报错: ORA-012560:TNS:协议适配器错误
- java SOF