Leetcode 20 Valid Parentheses
2015-10-03 11:31
489 查看
Valid Parentheses
Total Accepted: 71209 Total Submissions: 265268 Difficulty: Easy
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.
这道题我的实现方法很简单,而这应该也是成对括号问题的通用处理方法。即建立一个堆栈,然后遍历字符串如果遇到左括号’(‘,’[‘,’{‘,就入栈,如果遇到右括号’)’,’]’,’}’就看当前栈顶的元素,如果是与之匹配的左括号,那就让这个左括号出栈,否则,匹配就是错误的返回false,当数组都遍历一遍后,我们查看如果栈是否为空,如果为空,说明所有括号都得到匹配,返回true,否则返回false。
下面是完整代码:
Total Accepted: 71209 Total Submissions: 265268 Difficulty: Easy
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.
这道题我的实现方法很简单,而这应该也是成对括号问题的通用处理方法。即建立一个堆栈,然后遍历字符串如果遇到左括号’(‘,’[‘,’{‘,就入栈,如果遇到右括号’)’,’]’,’}’就看当前栈顶的元素,如果是与之匹配的左括号,那就让这个左括号出栈,否则,匹配就是错误的返回false,当数组都遍历一遍后,我们查看如果栈是否为空,如果为空,说明所有括号都得到匹配,返回true,否则返回false。
下面是完整代码:
#include <iostream> #include <stdio.h> using namespace std; bool isValid(char* s) { int size = strlen(s); char *stack = (char*)malloc(sizeof(char) * size); int top = -1; for(int i = 0; i < size; i++) { switch(s[i]) { case '(': top++; stack[top] = '('; break; case '{': top++; stack[top] = '{'; break; case '[': top++; stack[top] = '['; break; case ')': { if(top >=0 && stack[top] == '(') top--; else return false; break; } case '}': { if(top >=0 && stack[top] == '{') top--; else return false; break; } case ']': { if(top >=0 && stack[top] == '[') top--; else return false; break; } } } if(top == -1) return true; else return false; } int main() { char s[100]; scanf("%s",s); cout<<isValid(s)<<endl; }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解