1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
class Solution { static Map<String,String> map=new HashMap<>();
static{ map.put("(",")"); map.put("[","]"); map.put("{","}"); map.put("(",")"); } Stack<String> in=new Stack<>(); Stack<String> out=new Stack<>(); public boolean isValid(String s) { if("".equals(s)) return true; in.addAll( Arrays.asList(s.replace(" ","").split(""))); if(in.size()<2) return false; while(!in.isEmpty()){
if(null==map.get(in.peek())){ out.push(in.peek()); in.pop(); continue; } if(out.isEmpty()){ out.push(in.peek()); in.pop(); continue; } if(!(out.peek()).equals(map.get(in.peek()))){ out.push(in.peek()); in.pop(); continue; } out.pop(); in.pop(); } if(!out.isEmpty()) return false; return true; } }
public boolean isValid(String s) { s=s.replaceAll("\\(","c"); s=s.replaceAll("\\)","x"); s=s.replaceAll("\\[","a"); s=s.replaceAll("\\]","z"); s=s.replaceAll("\\{","b"); s=s.replaceAll("\\}","y"); while(true){ s=s.replace("cx",""); s=s.replace("az",""); s=s.replace("by",""); if(!s.contains("cx")&&!s.contains("az")&&!s.contains("by")) break; if("".equals(s)) return true; } if(!"".equals(s)) return false; return true; }
class Solution { public boolean isValid(String s) { while (s.contains("{}")||s.contains("[]")|| s.contains("()")){ if(s.contains("{}")) s=s.replace("{}",""); if(s.contains("()")) s=s.replace("()",""); if(s.contains("[]")) s=s.replace("[]",""); }
return s.isEmpty(); } }
|