2337.移动片段得到字符串
链接:2337.移动片段得到字符串
难度:Medium
标签:双指针、字符串
简介:如果在移动字符串 start 中的片段任意次之后可以得到字符串 target ,返回 true ;否则,返回 false 。
题解 1 - cpp
- 编辑时间:2023-08-21
- 执行用时:56ms
- 内存消耗:18.6MB
- 编程语言:cpp
- 解法介绍:判断start的L都在target右侧,R都在target左侧。
class Solution {
public:
    bool canChange(string start, string target) {
        int n = start.size(), i1 = 0, i2 = 0;
        while (i1 < n && start[i1] == '_') i1 += 1;
        while (i2 < n && target[i2] == '_') i2 += 1;
        while (i1 < n && i2 < n) {
            if (start[i1] != target[i2]) return false;
            if (start[i1] == 'L' && i1 < i2) return false;
            if (start[i1] == 'R' && i1 > i2) return false;
            i1 += 1;
            i2 += 1;
            while (i1 < n && start[i1] == '_') i1 += 1;
            while (i2 < n && target[i2] == '_') i2 += 1;
        }
        return i1 == n && i2 == n;
    }
};
题解 2 - rust
- 编辑时间:2023-08-21
- 执行用时:12ms
- 内存消耗:3.1MB
- 编程语言:rust
- 解法介绍:同上。
pub fn str_to_vec(s: &String) -> Vec<char> {
    s.chars().collect()
}
impl Solution {
    pub fn can_change(start: String, target: String) -> bool {
        let start = str_to_vec(&start);
        let target = str_to_vec(&target);
        let n = start.len();
        let (mut i1, mut i2) = (0, 0);
        while i1 < n && start[i1] == '_' {
            i1 += 1;
        }
        while i2 < n && target[i2] == '_' {
            i2 += 1;
        }
        while (i1 < n && i2 < n) {
            if start[i1] != target[i2] {
                return false;
            }
            if start[i1] == 'L' && i1 < i2 {
                return false;
            }
            if start[i1] == 'R' && i1 > i2 {
                return false;
            }
            i1 += 1;
            i2 += 1;
            while i1 < n && start[i1] == '_' {
                i1 += 1;
            }
            while i2 < n && target[i2] == '_' {
                i2 += 1;
            }
        }
        i1 == n && i2 == n
    }
}
题解 3 - python
- 编辑时间:2023-08-21
- 执行用时:240ms
- 内存消耗:16.43MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def canChange(self, start: str, target: str) -> bool:
        n = len(start)
        i1 = i2 = 0
        while i1 < n and start[i1] == '_':
            i1 += 1
        while i2 < n and target[i2] == '_':
            i2 += 1
        while i1 < n and i2 < n:
            if start[i1] != target[i2]:
                return False
            if start[i1] == 'L' and i1 < i2:
                return False
            if start[i1] == 'R' and i1 > i2:
                return False
            i1 += 1
            i2 += 1
            while i1 < n and start[i1] == '_':
                i1 += 1
            while i2 < n and target[i2] == '_':
                i2 += 1
        return i1 == n and i2 == n