20. Valid Parentheses leetcode java
2018-01-15 11:32
701 查看
1.题目
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.
给定一个包含(){}[]的字符串,判断它是否是有效括号。
2.思路
用栈解决这个问题,用两个栈,s1和s2,s1里按序push进字符串s
①如果s2不为空,取s1和s2栈顶字符进行比较,如果满足isequal那么s2的栈顶pop掉
②如果s2为空,那么将s1栈顶push进s2
循环结束如果s2为空,那么这个字符有效,否则无效。
isequal函数的功能在于看传到这个函数的两个字符是否能配成一对,而且是有序的一对,比如“()“是一对,但是“)(”不是。
注意字符串相等不能用==,而是要用equals()函数。
3.程序
class Solution {
public boolean isValid(String s) {
Stack<String> s1=new Stack<String>();
Stack<String> s2=new Stack<String>();
String temp;
for(int i=0;i<s.length();i++){
s1.push(s.substring(i,i+1));
}
while(!s1.isEmpty()){
temp=s1.pop();
if(!s2.isEmpty()){
if(isequal(temp,s2.peek())) {
s2.pop();
}
else {
s2.push(temp);
}
}
else
s2.push(temp);
}
if(s2.isEmpty())
return true;
return false;
}
public boolean isequal(String a,String b) {
if((a.equals("{")&&b.equals("}"))||(a.equals("[")&&b.equals("]"))||(a.equals("(")&&b.equals(")")))
return true;
return false;
}
}
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.
给定一个包含(){}[]的字符串,判断它是否是有效括号。
2.思路
用栈解决这个问题,用两个栈,s1和s2,s1里按序push进字符串s
①如果s2不为空,取s1和s2栈顶字符进行比较,如果满足isequal那么s2的栈顶pop掉
②如果s2为空,那么将s1栈顶push进s2
循环结束如果s2为空,那么这个字符有效,否则无效。
isequal函数的功能在于看传到这个函数的两个字符是否能配成一对,而且是有序的一对,比如“()“是一对,但是“)(”不是。
注意字符串相等不能用==,而是要用equals()函数。
3.程序
class Solution {
public boolean isValid(String s) {
Stack<String> s1=new Stack<String>();
Stack<String> s2=new Stack<String>();
String temp;
for(int i=0;i<s.length();i++){
s1.push(s.substring(i,i+1));
}
while(!s1.isEmpty()){
temp=s1.pop();
if(!s2.isEmpty()){
if(isequal(temp,s2.peek())) {
s2.pop();
}
else {
s2.push(temp);
}
}
else
s2.push(temp);
}
if(s2.isEmpty())
return true;
return false;
}
public boolean isequal(String a,String b) {
if((a.equals("{")&&b.equals("}"))||(a.equals("[")&&b.equals("]"))||(a.equals("(")&&b.equals(")")))
return true;
return false;
}
}
相关文章推荐
- leetcode-java-20. Valid Parentheses
- (Java)LeetCode-20. Valid Parentheses
- 20. Valid Parentheses-leetcode-java
- LeetCode 20 Valid Parentheses (C,C++,Java,Python)
- [leetcode-20]Valid Parentheses(java)
- Java [leetcode 20]Valid Parentheses
- [leetcode]20. Valid Parentheses(java)
- Leetcode:20. Valid Parentheses(JAVA)
- LeetCode20 Valid Parentheses的java 题解
- [leetcode]20. Valid Parentheses(Java)
- leetcode 20. Valid Parentheses ---java
- LeetCode 20 : Valid Parentheses (Java)
- LeetCode 20 — Valid Parentheses(C++ Java Python)
- leetcode_20_Valid Parentheses (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