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,则栈弹两次,否则返回假。
如果最后栈空,说明合法。