leetcode_Valid Parentheses
2015-05-21 09:14
302 查看
描述:
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
思路:
很简单的字符串匹配问题,直接用栈就可以实现,为使程序更加高效,当要匹配的字符种类比较多的时候可以考虑用HashMap来保存匹配对
代码:
用if else来比较匹配对
用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();
}else
st.push(s.charAt(i));
}
return st.empty();
}
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();
}else
st.push(s.charAt(i));
}
return st.empty();
}
相关文章推荐
- LeetCode——Longest Valid Parentheses
- leetcode-20 Valid Parentheses
- LeetCode | Valid Parentheses(括号匹配)
- leetcode 20. Valid Parentheses
- [LeetCode] Valid Parentheses
- LeetCode 020 Valid Parentheses
- LeetCode | Longest Valid Parentheses
- 【LeetCode】Longest Valid Parentheses 解题报告
- [leetcode刷题系列]Longest Valid Parentheses
- leetcode 32 Longest Valid Parentheses
- LeetCode--Valid Parentheses
- [LeetCode] Valid Parentheses
- 【Leetcode】【python】Valid Parentheses
- [LeetCode]Longest Valid Parentheses(!!!)
- leetcode Valid Parentheses
- Leetcode#20: Valid Parentheses
- leetcode第一刷_Longest Valid Parentheses
- LeetCode: Valid Parentheses [020]
- LeetCode 20: Valid Parentheses
- leetcode-Valid Parentheses