[Leetcode 20] 20 Valid Parentheses
2013-05-19 04:16
302 查看
Problem:
Given a string containing just the characters
The brackets must close in the correct order,
Analysis:
Use a stack to help. If the element is '(', '[', '{', push it onto stack. If the element is ')', ']', '}', pop one element from stack and see if they match with each other. If not match, then return false;
Other cases may cause false result are: 1. Meet with ')', ']', '}', but the stack is empty; 2. The string has been processed, but the stack is not empty.
The time complexity is O(n), the space complexity is O(n) in worst case, O(1) in best case;
Code:
View Code
Attention:
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:
Use a stack to help. If the element is '(', '[', '{', push it onto stack. If the element is ')', ']', '}', pop one element from stack and see if they match with each other. If not match, then return false;
Other cases may cause false result are: 1. Meet with ')', ']', '}', but the stack is empty; 2. The string has been processed, but the stack is not empty.
The time complexity is O(n), the space complexity is O(n) in worst case, O(1) in best case;
Code:
public class Solution { public boolean isValid(String s) { // Start typing your Java solution below // DO NOT write main() function char[] stack = new char[100]; int tos = 0; char tmp; for (int i=0; i<s.length(); ++i) { tmp = s.charAt(i); switch(tmp) { case '(': case '[': case '{': stack[tos++] = tmp; break; case ')': if (tos==0 || stack[--tos]!='(') return false; break; case '}': if (tos==0 || stack[--tos]!='{') return false; break; case ']': if (tos==0 || stack[--tos]!='[') return false; break; } } if (tos != 0) return false; else return true; } }
View Code
Attention:
相关文章推荐
- LeetCode | 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- 蜗牛慢慢爬 LeetCode 20. Valid Parentheses [Difficulty: Easy]
- Leetcode_20_Valid Parentheses
- [LeetCode]20. Valid Parentheses
- Leetcode-20. Valid Parentheses
- LeetCode 20. Valid Parentheses(合法括号序列)
- leetcode:20 Valid Parentheses-每日编程第三十七题
- LeetCode - 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- LeetCode 20 Valid Parentheses
- Leetcode 20 Valid Parentheses
- 【一天一道LeetCode】#20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode_20---Valid Parentheses
- Leetcode 20. Valid Parentheses - javascript
- LeetCode 20 Valid Parentheses
- [leetcode] 【栈】 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses