给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:添加链接描述
String类的库函数
class Solution {
public boolean isValid(String s) {
int length = s.length() / 2;
for (int i = 0; i < length; i++) {
s = s.replace("()", "").replace("{}", "").replace("[]", "");
}
return s.length() == 0;
}
public static void main(String[] args) {
Solution s = new Solution();
boolean flag = s.isValid("(([]){})");
System.out.println(flag);
}
}
栈机制,闭合符号充分体现了栈机制,压栈,出栈。
import java.util.Stack;
class Solution {
public boolean isValid(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();
}
public static void main(String[] args) {
Solution s = new Solution();
boolean flag = s.isValid("(([]){})");
System.out.println(flag);
}
}