Valid Parentheses LeetCode java
2015-12-29 14:53
459 查看
Given a string containing just the characters
The brackets must close in the correct order,
三种括号组成的字符串,进行有效性判断,用普通的方法进行遍历比较,费事不说,种类的变化也不胜枚举。
这里,我们用了stack的特性,来进行比较。为(,【,{则直接入栈,为)】}则从stack弹出顶部的元素进行比较。
代码如下
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] c = s.toCharArray();
for(int i = 0; i<c.length;i++){
if(c[i] == '(' || c[i] == '[' || c[i] == '{'){
stack.push(c[i]);
}else if(c[i] == ')' || c[i] == ']' ||c[i] == '}'){
if(stack.empty()){
return false;
}else{
char ch = stack.pop();
if( ch == '(' && c[i] == ')')continue;
if( ch == '[' && c[i] == ']')continue;
if( ch == '{' && c[i] == '}')continue;
else return false;
}
}
}
if(stack.empty()) return true;
else return false;
}
}
95c6
'(',
')',
'{',
'}',
'['and
']', determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are all valid but
"(]"and
"([)]"are not.
三种括号组成的字符串,进行有效性判断,用普通的方法进行遍历比较,费事不说,种类的变化也不胜枚举。
这里,我们用了stack的特性,来进行比较。为(,【,{则直接入栈,为)】}则从stack弹出顶部的元素进行比较。
代码如下
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
char[] c = s.toCharArray();
for(int i = 0; i<c.length;i++){
if(c[i] == '(' || c[i] == '[' || c[i] == '{'){
stack.push(c[i]);
}else if(c[i] == ')' || c[i] == ']' ||c[i] == '}'){
if(stack.empty()){
return false;
}else{
char ch = stack.pop();
if( ch == '(' && c[i] == ')')continue;
if( ch == '[' && c[i] == ']')continue;
if( ch == '{' && c[i] == '}')continue;
else return false;
}
}
}
if(stack.empty()) return true;
else return false;
}
}
95c6
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [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 题解