topic:
Given a string that only includes'(',')','{','}','[',']', judge whether the string is valid.
A valid string must meet:
1. An empty string can be considered a valid string.
2. The left and right brackets must be closed in the correct order.
Such as:
Legal: {[]}()
Illegal: {[}]
**
Implementation code:
**
Method 1:
// 多次循环替换括号,如果替换后的字符串还是替换前的字符串,则为无效字符串
public static boolean isValid(String s) {
String str="";
while(!s.equals("")){
str=s.replace("{}","").replace("[]","").replace("()","");
if(s==str){
return false;
}
s=str;
}
return true;
}
Method 2:
// 遇到一个正向括号,将对应的反向括号填入栈中
// 遇到反向括号,将栈中的正向括号拿出比较
public static boolean isValid1(String s) {
Stack<Character> stack = new Stack<Character>();
for(char c: s.toCharArray()){
if(c=='(')stack.push(')');
else if(c=='[')stack.push(']');
else if(c=='{')stack.push('}');
else if(stack.isEmpty()||c!=stack.pop())return false;
}
return stack.isEmpty();
}