[leet code] Valid Parentheses
来源:互联网 发布:手工西装淘宝 编辑:程序博客网 时间:2024/06/08 15:25
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.
Analysis:
This is a simple problem, but easy to make mistake when implementing. Idea of which is to utilize a stack to match symbols.
public class Solution { public boolean isValid(String s) { if(s.length()<=1) return false; Stack<Character> symbol = new Stack<Character>(); for (int i =0; i<s.length(); i++){ if(s.charAt(i) == '(' || s.charAt(i)=='{' || s.charAt(i)=='[') symbol.push(s.charAt(i)); else if (s.charAt(i)==')') { if(symbol.isEmpty() == true || symbol.pop()!='(') return false; } else if (s.charAt(i)=='}') { if(symbol.isEmpty() == true || symbol.pop()!='{') return false; } else if (s.charAt(i)==']') { if(symbol.isEmpty() == true || symbol.pop()!='[') return false; } else return false; } if (symbol.isEmpty() == true) return true; return false; }}
Note that always check if stack is empty before .pop().
0 0
- [leet code] Valid Parentheses
- Leet Code 20 Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- [leet code] Generate Parentheses
- [leet code] Valid Sudoku
- Leet Code OJ: Valid Number
- CODE 111: Valid Parentheses
- 【Leet Code】 242. Valid Anagram--easy
- CODE 101: Longest Valid Parentheses
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 125. Valid Palindrome [Difficulty: Easy]
- leetcode 日经贴,python code -Valid Parentheses
- leetcode 日经贴,python code -Longest Valid Parentheses
- leetcode 日经贴,Cpp code -Valid Parentheses
- Leet -- Generate Parentheses
- [leet code] Gray Code
- Valid Parentheses
- 一道面试题 - 找最长固定unique个数的子串
- Homebrew的安装与使用
- 摘抄代码片段
- 渣降临@Palindrome Partitioning II
- cocos2dx 精灵监听触摸事件
- [leet code] Valid Parentheses
- 数据库中创建索引的准则
- 第一章:前言
- bzoj1507
- 开放系统互连参考模型(OSI)-网络中的七层协议
- oracle11G 处理控制文件的丢失
- 物联网需要自己的专有操作系统
- day one
- 第二章:OSGi简介