跳转至

1003. 检查替换后的词是否有效

题目描述

给你一个字符串 s ,请你判断它是否 有效

字符串 s 有效 需要满足:假设开始有一个空字符串 t = "" ,你可以执行 任意次 下述操作将 t 转换为 s

  • 将字符串 "abc" 插入到 t 中的任意位置。形式上,t 变为 tleft + "abc" + tright,其中 t == tleft + tright 。注意,tlefttright 可能为

如果字符串 s 有效,则返回 true;否则,返回 false

 

示例 1:

输入:s = "aabcbc"
输出:true
解释:
"" -> "abc" -> "aabcbc"
因此,"aabcbc" 有效。

示例 2:

输入:s = "abcabcababcc"
输出:true
解释:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
因此,"abcabcababcc" 有效。

示例 3:

输入:s = "abccba"
输出:false
解释:执行操作无法得到 "abccba" 。

 

提示:

  • 1 <= s.length <= 2 * 104
  • s 由字母 'a''b''c' 组成

解法

方法一:栈

我们观察题目中的操作,可以发现,每一次都会在字符串的任意位置插入字符串 "abc",所以每次插入操作之后,字符串的长度都会增加 $3$。如果字符串 $s$ 有效,那么它的长度一定是 $3$ 的倍数。因此,我们先对字符串 $s$ 的长度进行判断,如果不是 $3$ 的倍数,那么 $s$ 一定无效,可以直接返回 false

接下来我们遍历字符串 $s$ 的每个字符 $c$,我们先将字符 $c$ 压入栈 $t$ 中。如果此时栈 $t$ 的长度大于等于 $3$,并且栈顶的三个元素组成了字符串 "abc",那么我们就将栈顶的三个元素弹出。然后继续遍历字符串 $s$ 的下一个字符。

遍历结束之后,如果栈 $t$ 为空,那么说明字符串 $s$ 有效,返回 true,否则返回 false

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是字符串 $s$ 的长度。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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();
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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();
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
}

评论