Check If Word Is Valid After Substitutions——LeetCode

336 阅读1分钟

题目描述

题解

  • 方法一

找出字符串中的“abc”并删除,直到找不到“abc”为止。此时判断字符串是否为空。如果是空的话,说明字符串是合法的。

  • 方法二

利用栈来判断字符串是否合法,遇到c就出栈前两个,碰到前两个为“b”和“c”这说明暂时合法,否则字符串不合法。将整个字符串遍历完后,查看栈中是否为空,为空的话说明字符串合法。

代码

class Solution {
    public boolean isValid(String S) {
        // 方法一
        // System.out.println(S.substring(1,4));
        // while(S.length() != 0){
        //     int index = S.indexOf("abc");
        //     if(index != -1){
        //         S = S.substring(0,index) + S.substring(index+3,S.length());
        //     }else{
        //         break;
        //     }
        //     // System.out.println(S);
        // }
        // if(S.length() == 0){
        //     return true;
        // }
        // return false;
        // 方法二
        Stack<Character> s = new Stack<>();
        for(char c:S.toCharArray()){
            if(c == 'c'){
                if(s.isEmpty() || s.pop() != 'b'){
                    return false;
                }
                if(s.isEmpty() || s.pop() != 'a'){
                    return false;
                }
            }else{
                s.push(c);
            }
        }
        if(s.isEmpty()){
            return true;
        }
        return false;
    }
}