We are given that the string "abc"
is valid.
From any valid string V
, we may split V
into two pieces X
and Y
such that X + Y
(X
concatenated with Y
) is equal to V
. (X
or Y
may be empty.) Then, X + "abc" + Y
is also valid.
If for example S = "abc"
, then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc"
. Examples of invalid strings are: "abccba"
, "ab"
, "cababc"
, "bac"
.
Return true
if and only if the given string S
is valid.
Example 1:
Input: "aabcbc"
Output: true
Explanation:
We start with the valid string "abc".
Then we can insert another "abc" between "a" and "bc", resulting in "a" + "abc" + "bc" which is "aabcbc".
Example 2:
Input: "abcabcababcc"
Output: true
Explanation:
"abcabcabc" is valid after consecutive insertings of "abc".
Then we can insert "abc" before the last letter, resulting in "abcabcab" + "abc" + "c" which is "abcabcababcc".
Example 3:
Input: "abccba"
Output: false
Example 4:
Input: "cababc"
Output: false
Note:
1 <= S.length <= 20000
S[i]
is'a'
,'b'
, or'c'
题意:设"abc"为一个合法的字符串。对于任意合法串V,我们可以将其分为X,Y两部分,其中X+Y=V。则X+"abc"+Y也是一个合法的字符串。给出一个字符串,问是否合法。
方法一:使用了string的find函数和erase函数,当串中包含"abc"子串时,将其删除,最后判断串是否为空即可。
class Solution {
public:
stack<char>st;
bool isValid(string S) {
int flag=1,pos;
while(S!=""&&flag==1){
flag=0;
//pos=S.find(t) 在S中查找子串t,存在返回其开始位置,没有则返回-1
if((pos=S.find("abc"))!=-1){
flag=1;
//S.erase(pos,len) 从pos开始,删除len个字母
S.erase(pos,3);
}
}
if(S=="")
return 1;
else
return 0;
}
};
方法二:借助栈实现。根据题意可知,每个字符串都可以看作是由若干个"abc"子串在保持原顺序的情况下插入其他合法子串得到的。将未匹配的字符入栈,当前元素为c时,则栈中最后两个元素应该为'a'和'b',此时将它们出栈,继续遍历下一元素即可。若不为'a'和'b',则由该串不合法。
class Solution {
public:
bool isValid(string S) {
vector<char> stack;
for (char c : S) {
if (c == 'c') {
int n = stack.size();
if (n < 2 || stack[n - 1] != 'b' || stack[n - 2] != 'a') return false;
stack.pop_back(), stack.pop_back();
} else {
stack.push_back(c);
}
}
return stack.size() == 0;
}
};