comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
Medium |
1426 |
Weekly Contest 126 Q2 |
|
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.
Constraints:
1 <= s.length <= 2 * 104
s
consists of letters'a'
,'b'
, and'c'
If the string is valid, it's length must be the multiple of
We traverse the string and push every character into the stack "abc"
, we pop the top three elements. Then we continue to traverse the next character of the string
When the traversal is over, if the stack true
, otherwise return false
.
The time complexity is
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 3:
return False
t = []
for c in s:
t.append(c)
if ''.join(t[-3:]) == 'abc':
t[-3:] = []
return not t
class Solution {
public boolean isValid(String s) {
if (s.length() % 3 > 0) {
return false;
}
StringBuilder t = new StringBuilder();
for (char c : s.toCharArray()) {
t.append(c);
if (t.length() >= 3 && "abc".equals(t.substring(t.length() - 3))) {
t.delete(t.length() - 3, t.length());
}
}
return t.isEmpty();
}
}
class Solution {
public:
bool isValid(string s) {
if (s.size() % 3) {
return false;
}
string t;
for (char c : s) {
t.push_back(c);
if (t.size() >= 3 && t.substr(t.size() - 3, 3) == "abc") {
t.erase(t.end() - 3, t.end());
}
}
return t.empty();
}
};
func isValid(s string) bool {
if len(s)%3 > 0 {
return false
}
t := []byte{}
for i := range s {
t = append(t, s[i])
if len(t) >= 3 && string(t[len(t)-3:]) == "abc" {
t = t[:len(t)-3]
}
}
return len(t) == 0
}
function isValid(s: string): boolean {
if (s.length % 3 !== 0) {
return false;
}
const t: string[] = [];
for (const c of s) {
t.push(c);
if (t.slice(-3).join('') === 'abc') {
t.splice(-3);
}
}
return t.length === 0;
}