这是第一次思考出来的代码,如果有改进的还会继续更新,这个代码,就是内存消耗太大,还有消耗时间长,总结下来,就是差劲,欢迎各位在评论区评论。
package com.shengda.Demo0Likou;
import java.util.ArrayList;
import java.util.Map;
public class ss {
public static void main(String[] args) {
Solution s = new Solution();
String str = new String("()[]{}");
boolean valid = s.isValid(str);
System.out.println(valid);
}
}
class Solution {
public boolean isValid(String s) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(0);
for (int i = 0; i < s.length(); i++) {
boolean bl = getValid(arr,s.charAt(i));
if (!bl) return false;
}
if (arr.size() == 1) return true;
else return false;
}
private boolean getValid(ArrayList<Integer> arr,char charAt) {
Map<String,Integer> map = Map.of("(",1,")",-1,"{",2,"}",-2,"[",3,"]",-3);
int s = map.get(String.valueOf(charAt));
if(arr.get(arr.size()-1)+s==0) {
arr.remove(arr.size()-1);
return true;
} else if (arr.get(arr.size()-1)+s < 0) return false;
else {
arr.add(s);
return true;
}
}
}
}
|