法一堆栈的思想,主要考察堆栈的使用,注意字符串转字符数组可以使用toCharArray
也可直接s.charAt(i)
法二字符串修改的方法
class Solution {
public boolean isValid(String s) {
char[] array = s.toCharArray();
Stack<Character> stack = new Stack<>();
Character temp =' ';
for(int i=0;i<array.length;i++){
if(!stack.empty()){
temp=stack.peek();
}else{
temp=' ';
}
if(array[i]==')' && temp.equals('(')){
stack.pop();
}else if(array[i]==']' && temp.equals('[')){
stack.pop();
}else if(array[i]=='}' && temp.equals('{')){
stack.pop();
}else {
stack.push(array[i]);
}
}
return stack.empty();
}
}
class Solution {
public boolean isValid(String s) {
while(s.contains("()") || s.contains("[]") || s.contains("{}")){
s=s.replaceAll("\\(\\)","");
s=s.replaceAll("\\[]","");
s=s.replaceAll("\\{}","");
}
return s.length()==0;
}
}
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
while "()" in s or "[]" in s or "{}" in s :
s=s.replace("()","")
s=s.replace("[]","")
s=s.replace("{}","")
return s==""```