2021年12月2日 星期四

[LeetCode] 1003. Check If Word Is Valid After Substitutions

轉自LeetCode

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.

 

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


這題可以看作是 20. Valid Parentheses 的衍生題

想法稍微變一下,從原本的左括號右括號配對,變成 abc 配對

意思是,c 的前面,一定要有 ab,不然就是不合法

所以,當遇到 c 的時候,去檢查前面是否有b和a

如果沒有,就回傳 false,有就繼續檢查下去

最後檢查 stack 裡面是否都用光了

kotlin

沒有留言:

張貼留言