题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合
示例
输入:s = “()”
输出:true
class Solution {
public boolean isValid(String s) {
if (s.length()<2 || s.length()%2 != 0) { // 字符串长度为1,输出为false;长度为0,输出为true
if (s.isEmpty()) {
System.out.println(true);
return true;
}
else{
System.out.println(false);
return false;
}
}
int count = 0;
int length = s.length();
while (count < length/2){ // 依次用成对的符号替换
s = s.replace("{}","").replace("[]","").replace("()","");
count ++;
}
if (s.length()>0){
System.out.println(false);
return false;
}
else{
System.out.println(true);
return true;
}
}
}