leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
来源:互联网 发布:广电网络宽带用哪条线 编辑:程序博客网 时间:2024/04/27 17:19
Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
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.
具体代码如下:
public class Solution { public boolean isValid(String s) { Stack<Character> st = new Stack<Character>(); char[] ch = s.toCharArray(); int len = ch.length; //如果长度为奇数,肯定无效 if((len & 1) != 0){ return false; } for(int i = 0; i < len; i++){ if(st.isEmpty()){//栈为空,直接入栈 st.push(ch[i]); }else{//不为空则讨论栈顶元素是否与ch[i]配对。配对也出栈 if(isMatch(st.peek(),ch[i])){//是否配对 st.pop();//栈顶元素出栈 }else{ st.push(ch[i]);//不配对入栈 } } } return st.isEmpty(); } //a为栈顶元素,b为字符串最前元素 public static boolean isMatch(char a, char b){ switch(a){ case '(': if(b == ')') return true; else return false; case '{': if(b == '}') return true; else return false; case '[': if(b == ']') return true; else return false; default : return false; } }}
0 0
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- leetCode 32.Longest Valid Parentheses (有效的最大括号) 解题思路和方法
- 【LeetCode】- Valid Parentheses(有效的括号)
- LeetCode-20-Valid Parentheses(有效的括号)
- leetCode 22.Generate Parentheses (生成括号) 解题思路和方法
- leetcode Valid Parentheses 有效括号
- leetCode 36.Valid Sudoku(有效的数独) 解题思路和方法
- Leetcode刷题记——20. Valid Parentheses (有效的括号即括号匹配)
- LeetCode--Longest Valid Parentheses(最长有效的括号)
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- LeetCode OJ 之 Valid Parentheses(有效的括号判断)
- LeetCode 20 Valid Parentheses(有效的括号)
- LeetCode 20. Valid Parentheses--验证括号是否有效
- Leetcode#20. Valid Parentheses(有效括号-栈)
- Valid Parentheses 有效括号
- [leetcode]20. Valid Parentheses ,有效的括号符串python实现【easy】
- Longest Valid Parentheses 最长的有效括号
- Valid Parentheses有效的括号序列
- 黑马程序员—String类 (常见的操作有那些)
- ffmpeg一些filter用法、以及一些功能命令
- 算法一:排序和数据结构体
- Android Http Server
- TTS---科大讯飞语音合成
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- Python WSGI接口
- 92.将字母按规定转换
- 黑马程序员——Java网络编程-整理笔记
- 设置某个类使用或者禁用ARC
- PHP学习小记
- python locals函数
- Intent传递类内容
- gcc 参数记录