Given a string
A string
- Insert string
"abc" into any position int . More formally,t becomestleft + "abc" + tright , wheret == tleft + tright . Note thattleft andtright may be empty.
Return
Example 1:
Input: s = "aabcbc" Output: true Explanation: "" -> "abc" -> "aabcbc" Thus, "aabcbc" is valid.
Example 2:
Input: s = "abcabcababcc" Output: true Explanation: "" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc" Thus, "abcabcababcc" is valid.
Example 3:
Input: s = "abccba" Output: false Explanation: It is impossible to get "abccba" using the operation.
Example 4:
Input: s = "cababc" Output: false Explanation: It is impossible to get "cababc" using the operation.
Constraints:
1 <= s.length <= 2 * 104 s consists of letters'a' ,'b' , and'c'
Solution
想法稍微變一下,從原本的左括號右括號配對,變成 abc 配對
意思是,c 的前面,一定要有 ab,不然就是不合法
所以,當遇到 c 的時候,去檢查前面是否有b和a
如果沒有,就回傳 false,有就繼續檢查下去
最後檢查 stack 裡面是否都用光了
kotlin
沒有留言:
張貼留言