20. 有效的括号_字符串_简单

 

 这道题的思路就是使用栈来进行解决或者使用字符串操作来进行处理

 

 

package com.bupt;

import java.util.*;

public class T20 {



    public boolean isValid(String s){

        while (s.contains("{}") || s.contains("()") || s.contains("[]")){
            s = s.replace("{}","");
            s = s.replace("()","");
            s = s.replace("[]","");
        }
       return s.length()==0;

    }

    public boolean isValid(String str){
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {

            if(i==1)
            {
                System.out.println(System.identityHashCode(stack.peek()+""+str.charAt(i)));
                System.out.println(System.identityHashCode("{}"));
            }
            if (stack.isEmpty()){
                stack.push(str.charAt(i));
            }
            else if((stack.peek()+""+str.charAt(i)).equals("{}") ||(stack.peek()+""+str.charAt(i)).equals("[]") || (stack.peek()+""+str.charAt(i)).equals("()")){
//                System.out.println(stack.peek()+""+str.charAt(i));
                stack.pop();
            }else{
                stack.push(str.charAt(i));
            }
        }

        return stack.isEmpty();
    }
    public static void main(String[] args) {

        String a = "{}";
        System.out.println(a=="{}");
        System.out.println('{'+""+'}' == "{}");
        Scanner scanner = new Scanner(System.in);
        while (true){
            String str = scanner.next();
            boolean valid = new T20().isValid1(str);
//            System.out.println(valid);
        }

    }
}

 

posted @ 2021-09-17 14:24  你的雷哥  阅读(29)  评论(0编辑  收藏  举报