leetcode_Valid Parentheses
来源:互联网 发布:5个数相加等于100算法 编辑:程序博客网 时间:2024/05/28 17:06
描述:
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.
思路:
很简单的字符串匹配问题,直接用栈就可以实现,为使程序更加高效,当要匹配的字符种类比较多的时候可以考虑用HashMap来保存匹配对
代码:
用if else来比较匹配对
public boolean isValid(String s) { if(s==null||s.length()==0) return true; Stack<Character> st=new Stack<Character>(); char ch; int len=s.length(); for(int i=0;i<len;i++) { ch=s.charAt(i); if(!st.empty()) { if(ch==')'&&st.peek()=='(') { st.pop(); }else if(ch==']'&&st.peek()=='[') { st.pop(); } else if(ch=='}'&&st.peek()=='{') { st.pop(); }else st.push(ch); }else st.push(ch); } if(!st.empty()) return false; return true; }
用HashMap来保存匹配对
public boolean isValid(String s) {if (s == null || s.length() == 0)return true;Stack<Character> st = new Stack<Character>();Map<Character, Character> map = new HashMap<Character, Character>();map.put('(', ')');map.put('{', '}');map.put('[', ']');int len=s.length();for (int i = 0; i < len; i++) {if (!st.empty()&&map.containsKey(st.peek())&&s.charAt(i) == map.get(st.peek())) {st.pop();}elsest.push(s.charAt(i));}return st.empty();}
1 0
- Leetcode_valid-parentheses
- leetcode_Valid Parentheses
- LeetCode_Valid Parentheses
- Leetcode_valid-palindrome
- Leetcode_valid-sudoku
- Leetcode_Valid Palindrome
- LeetCode_Valid Sudoku
- leetcode_Valid Palindrome
- leetcode_Valid Number
- leetcode_Valid Sudoku
- leetcode_Valid Anagram
- leetcode_Valid Anagram_easy
- LeetCode_valid-anagram
- leetCode_Valid Number
- leetcode_Valid Perfect Square
- Leetcode_valid-number(updated c++ and python version)
- leetcode_Valid Sudoku and Sudoku Solver (数独游戏) _easy
- Generate Parentheses & Valid Parentheses
- Cordys SOA [即 WebService ]
- jstl中else替代方法,<c:else
- 网站访问统计系统Piwik安装使用:支持插件扩展统计媲美Google Analytics
- CvMat,Mat和IplImage之间的转化和拷贝
- hadoop中map和reduce的数量设置问题
- leetcode_Valid Parentheses
- easyui 创建datagrid
- Netty通信
- 浅谈php-Memcached常规应用与分布式部署方案-
- Remove Duplicates from Sorted List
- iOS开发 - 封装文件上传工具类
- hsql语言
- zend studio 的插件之一 Emmet
- 陈怡暖:2015.5.21早间最强现货黄金白银操作建议