Leetcode-20:Valid Parentheses
来源:互联网 发布:网络盈利模式 编辑:程序博客网 时间:2024/06/01 07:11
Question:
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.
给定一个字符串只包含字符“(”、“)”、“{”、“}”,“[”和“]”,判断输入的字符串是有效的。
括弧必须以正确的顺序关闭,“()”和“()[ ] { }”都是有效的但”(]”和“([)]”不是。
Answer:
使用栈来做。
当是左半边括弧的时候入栈,右半边括弧的时候栈顶元素出栈,判断此时栈顶元素是否和字符串此次括弧对应,对应则顺利出栈,不对应则返回false。字符串遍历完成后栈为空时返回true,非空时返回false。
import java.util.Stack;public class Solution { public boolean isValid(String s){ Stack<Character> stack = new Stack<Character>(); int x = 0; for(x=0;x<s.length();x++){ if(s.charAt(x)=='(' || s.charAt(x)=='[' || s.charAt(x)=='{'){ stack.push(s.charAt(x)); } if(s.charAt(x)==')'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='(') continue; else return false; } else if(s.charAt(x)==']'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='[') continue; else return false; } else if(s.charAt(x)=='}'){ if(stack.empty()) return false; char ch = stack.pop(); if(ch=='{') continue; else return false; } } if(stack.empty()){ return true; } else return false; }}
阅读全文
0 0
- LeetCode 20: Valid Parentheses
- LeetCode(20) Valid Parentheses
- leetcode 20 Valid Parentheses
- Leetcode【20】:Valid Parentheses
- leetcode 20-Valid Parentheses
- [leetcode 20] Valid Parentheses
- [Leetcode] 20 - Valid Parentheses
- LeetCode | #20 Valid Parentheses
- leetcode.20-----------Valid Parentheses
- [leetcode] 20 Valid Parentheses
- leetcode-20 Valid Parentheses
- leetCode #20 Valid Parentheses
- leetcode 20 Valid Parentheses
- Leetcode 20 Valid Parentheses
- LeetCode 20 - Valid Parentheses
- LeetCode 20: Valid Parentheses
- leetcode-20 Valid Parentheses
- leetcode 20 -- Valid Parentheses
- JS的十大经典算法排序
- 二叉树的各种遍历
- HDU 6044 Limited Permutation dfs + 组合数(读入挂)
- Python学习——动态类型简介
- 创建守护进程
- Leetcode-20:Valid Parentheses
- 碰撞检测
- Makefile.am Makefile.in Makefile与AutoMake关系
- JQuery语法规则
- webview无法弹出select选择框
- 入手arduino和W5100和乐为物联
- 常用集合的遍历方法和特点
- hdu2034 人见人爱A-B(C语言)
- Android Studio修改代码提示快捷键和eclipse一样