算法笔记12:删除字符串两端相同字符后的最短长度

123 阅读1分钟

1750.删除字符串两端相同字符后的最短长度

这道题目就是规则有点唬人,但其实很简单,按照它说的这五步完成就可以了。中间有一些特殊情况需要处理,比如说字符串长度为 1 的时候,其实也是走到终点了。因为按照题目要求,前、后缀不能为空也不能有交集,所以说字符串长度为 0 或 1 的时候,也是终点。

代码如下:

const minimumLength = (s) => {
    if (s.length < 2) {
        return s.length;
    }

    // if the first character and the last one are not the same
    // we reach the end
    if (s[0] !== s[s.length - 1]) {
        return s.length
    }

    // if all the characters are the same, then also the end
    let isAllSame = true
    for(let i = 0; i < s.length; i++) {
        if (s[i] !== s[0]) {
            isAllSame = false;
            break;
        }
    }
    if (isAllSame) {
        return 0;
    }

    const char = s[0];
    let left = 0;
    while(s[left] === char) {
        left++;
    }
    s = s.slice(left);

    let right = s.length - 1;
    while(s[right] === char) {
        right--;
    }
    s = s.slice(0, right + 1);

    return minimumLength(s);
};