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

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

 

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

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);
        }

    }
}

 

上一篇:KMP算法 next数组模板


下一篇:charAt()方法学习