Formatted question description: https://leetcode.ca/all/1003.html
1003. Check If Word Is Valid After Substitutions (Medium)
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'
Similar Questions:
Solution 1.
j
is read pointer and i
is write pointer. We always write s[j]
to s[i]
.
If the last 3 characters in front of i
is abc
, we clean them by i -= 3
.
In the end, return i == 0
.
// OJ: https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/
// Time: O(N)
// Space: O(1)
class Solution {
public:
bool isValid(string s) {
int i = 0, N = s.size();
for (int j = 0; j < N; ++j) {
s[i++] = s[j];
if (i >= 3 && s[i - 3] == 'a' && s[i - 2] == 'b' && s[i - 1] == 'c') i -= 3;
}
return i == 0;
}
};
Java
class Solution {
public boolean isValid(String S) {
Stack<Character> stack = new Stack<Character>();
int length = S.length();
for (int i = 0; i < length; i++) {
char c = S.charAt(i);
if (c == 'a' || c == 'b')
stack.push(c);
else {
if (stack.size() < 2)
return false;
char c2 = stack.pop();
char c1 = stack.pop();
if (c2 != 'b' || c1 != 'a')
return false;
}
}
return stack.isEmpty();
}
}