[1]题目概述
测试用例
[2]解题方法
1、方法一:
(常规思路)
class Solution {
public boolean isValid(String s) {
HashMap<Character,Character> map=new HashMap<>();
map.put('(',')');
map.put('{','}');
map.put('[',']');
LinkedList<Character> stack=new LinkedList<>();
for(int i=0;i<s.length();i++) {
char cur=s.charAt(i);
if(cur=='('||cur=='['||cur=='{'||stack.size()==0) {
stack.push(cur);
}else {
char top=stack.pop();
if(map.get(top)==null)
{
return false;
}
if(map.get(top)!=cur) {
return false;
}
}
}
if(stack.size()!=0) {
return false;
}else {
return true;
}
}
}
2、方法二:
(字符串的魅力)
class Solution {
public boolean isValid(String s) {
while(s.contains("()")||s.contains("{}")||s.contains("[]")) {
s=s.replace("()","");
s=s.replace("{}","");
s=s.replace("[]","");
}
System.out.println(s);
return s.equals("");
}
}