1003. Check If Word Is Valid After Substitutions
https://leetcode.com/problems/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 int
. More formally,t
becomestleft + "abc" + tright
, wheret == tleft + tright
. Note thattleft
andtright
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'
----
Intuition
Brute force is replacing all "abc" with "" till no more substituions are possible
-----
Time - O(N)
Space - O(N)
----
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean isValid(String s) { | |
Stack<Character> stack = new Stack<Character>(); | |
for (int i = 0; i < s.length(); i++) { | |
char ch = s.charAt(i); | |
if (ch == 'c') { | |
if (stack.isEmpty() || stack.pop() != 'b') { | |
return false; | |
} | |
if (stack.isEmpty() || stack.pop() != 'a') { | |
return false; | |
} | |
} else { | |
stack.push(ch); | |
} | |
} | |
return stack.isEmpty(); | |
} | |
} |