判断字符串括号是否合法-1

栈:先进后出(LIFO)顺序

Stack<Character> t = new Stack<Character>();

t.push('a');

t.push('b');

t.peek(); // 这里得到栈顶元素'b'

t.pop();  // 这里将栈顶元素'b'弹出

t.peek(); // 此时栈顶元素为'a'

t.pop();  // 这里将栈顶元素'a'弹出

【题目】字符串中只有字符'('和')'。合法字符串需要括号可以配对。比如:

输入:"()"

输出:true

解释:(),()(),(())是合法的。)(,()(,(()是非法的。

请你实现一个函数,来判断给定的字符串是否合法

package leetcode;

import java.util.Stack;

public class StackSolution {
    public boolean isValid(String s){
        // 当字符串本来就是空的时候,我们可以快速返回true
        if(s == null || s.length() == 0){
            return true;
        }
        // 当字符串长度为奇数的时候,不可能是一个有效的合法字符串
        if(s.length() % 2 ==1){
            return false ;
        }
        Stack<Character> t =  new Stack<Character>();
        for(int i=0 ; i < s.length();i++){
            // 取出字符
            char c= s.charAt(i);
            if(c =='('){
                // 如果是'(',那么压栈
                t.push(c);
            }else if(c == ')'){
                // 如果是')',那么就尝试弹栈
                if(t.empty()){
                    // 如果弹栈失败,那么返回false
                    return false ;
                }
                t.pop();
            }
        }
        return t.empty();
    }
    public static  void main(String[] argv){
        unitTest.run();
       // StackSolution stackSolution = new StackSolution();
        //System.out.println(stackSolution.isValid("())"));
    }
}
class unitTest {
    private static StackSolution stackSolution = new StackSolution();
    public static void testEmptyString(){
        assert stackSolution.isValid(null);
        assert stackSolution.isValid("");
    }
    public static void testSingleChar(){
        assert  !stackSolution.isValid("(");
        assert  !stackSolution.isValid(")");
    }
    public static void testTwoChars(){
        assert stackSolution.isValid("()");
        assert !stackSolution.isValid("((");
        assert !stackSolution.isValid("))");
        assert !stackSolution.isValid(")(");
    }
    public static void test3Chars(){
        assert !stackSolution.isValid("())");
        assert !stackSolution.isValid("(((");
        assert !stackSolution.isValid(")))");
        assert !stackSolution.isValid(")()");
    }
    public static void test4Chars(){
        assert stackSolution.isValid("()()");
        assert stackSolution.isValid("(())");
        assert !stackSolution.isValid("))((");
    }
    public static void testOther(){
        System.out.println("----testother start ------");
        assert stackSolution.isValid("()()()");
        assert stackSolution.isValid("((()))");
        assert stackSolution.isValid("()(())");
        assert !stackSolution.isValid("()(()(");
        System.out.println(!stackSolution.isValid("()(()("));
    }
    public static  void run(){
        testEmptyString();
        testSingleChar();
        testTwoChars();
        test3Chars();
        test4Chars();
        testOther();
        System.out.println("test over");
    }
}

 

posted on 2021-05-16 14:09  凌晨三点半的飞机  阅读(174)  评论(0编辑  收藏  举报