Check If Word Is Valid After Substitutions

Given a string s, determine if it is valid.

A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:

Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.
Return true if s is a valid string, otherwise, return false.

题意:空字符串,每次可以在任意位置插入abc,操作多次,判断字符串是否合法。

类比:括号匹配:每次可以在任意位置插入(),判断括号是否合法。

思路:栈(类似游戏祖玛)

遇到a,进栈。

遇到b,如果前面是a则进栈,否则返回假。

理解:不可能出现两个连续的b。

遇到c,如果前面是b,且前面的前面是a,则栈弹两次,否则返回假。

如果最后栈空,说明合法。

class Solution {
    public boolean isValid(String s) {
       Stack<Character>stack=new Stack<>();
       for(char c:s.toCharArray()){
           switch(c){
               case'a':
                stack.add(c);
                break;
                case'b':
                if(!stack.isEmpty()&&stack.peek()=='a')stack.add(c);
                else return false;
                break;
                default:
                 if(!(stack.size()>=2&&stack.pop()=='b'&&stack.pop()=='a'))return false;
           }
       }
       return stack.isEmpty();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.