LeetCode--Valid Parentheses
来源:互联网 发布:有道翻译无网络连接 编辑:程序博客网 时间:2024/06/05 12:11
这个题目我采用了两种方案,第一种方案代码行数相对较少,但效率稍低,第二种方案参照网上的进行改进代码行数相对多些,但效率稍高。
题目:
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.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
第一种解决方案:
import java.util.HashMap;import java.util.Map;public class Solution { public boolean isValid(String s) { Map<Character,Character> map=new HashMap<Character,Character>(); map.put(']','['); map.put('}','{'); map.put(')','('); Stack<Character> st=new Stack<Character>(); for(int i=0;i<s.length();i++){ Character c=s.charAt(i); if(c==']'||c=='}'||c==')'){ if(st.size()==0)return false; Character top=st.peek(); if(top.equals(map.get(c))){ st.pop(); }else{ return false; } }else{ st.push(c); } } return st.size()==0?true:false; }}
第二种解决方案:
import java.util.HashMap;import java.util.Map;public class Solution { public boolean isValid(String s) { Stack<Character> st = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if ((c == ']') || (c == '}') || (c == ')')) { if (st.empty()) { return false; } Character pre = st.peek(); switch (c) { case ')': if (pre == '(') { st.pop(); } else { return false; } break; case '}': if (pre == '{') { st.pop(); } else { return false; } break; case ']': if (pre == '[') { st.pop(); } else { return false; } break; } } else { st.push(c); } } return st.empty() ? true : false; }}
0 0
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode : Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Leetcode: Valid Parentheses
- leetcode 52: valid parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode-Valid Parentheses
- 对找工作功不可没——评《深入理解计算机系统》
- ios 判断网络是否可用
- 黑马程序员-管道流-RandomAccessFile-DateInputStream-ByteArrayOutputStream-转换流-InputStreamReader
- 客户端与服务器端的区别
- 黑马程序员---java基础----数组
- LeetCode--Valid Parentheses
- 线性链表C
- call 电话
- G - 好老师
- 将Axis2整合到Javaweb中发布Webservice
- jQuery form插件的使用
- 在OpenGL中怎样安装glut库
- OpenStack 最小化安装配置(七):Nova服务配置
- 浅谈C++多态性