1003.检查替换后的词是否有效
链接:1003.检查替换后的词是否有效
难度:Medium
标签:栈、字符串
简介:给你一个字符串 s ,请你判断它是否 有效 。
题解 1 - rust
- 编辑时间:2023-05-03
- 执行用时:4ms
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn is_valid(mut s: String) -> bool {
        while s != "" {
            let n = s.replace("abc", "");
            if n == s {
                return false;
            }
            s = n;
        }
        s == ""
    }
}
题解 2 - cpp
- 编辑时间:2023-05-03
- 执行用时:328ms
- 内存消耗:8.4MB
- 编程语言:cpp
- 解法介绍:一直找abc子串,替换成空串,直到不能再替换。
class Solution {
public:
    bool isValid(string s) {
        string next;
        do {
            int p = s.find("abc", 0);
            if (p == -1) return false;
            next = s.replace(p, 3, "");
        } while (next != "");
        return true;
    }
};
题解 3 - typescript
- 编辑时间:2023-05-03
- 执行用时:184ms
- 内存消耗:48.3MB
- 编程语言:typescript
- 解法介绍:遍历。
function isValid(s: string): boolean {
    while (s != "") {
        const n = s.replace("abc", "");
        if (n == s) return false;
        s = n;
    }
    return s == "";
};
题解 4 - python
- 编辑时间:2023-05-03
- 执行用时:56ms
- 内存消耗:16.2MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def isValid(self, s: str) -> bool:
        while s != "":
            n = s.replace("abc", "")
            if n == s: return False
            s = n
        return s == ""