Problem Description

Given a string S consisting of lowercase letters, the duplicate removal operation selects two adjacent and identical letters and removes them.

Repeat the deduplication operation on S until it can no longer be deleted.

Returns the final string after all deduplication operations are done. The answer is guaranteed to be unique.

Example:

 输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。
之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
Likou original title address: https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string

solution

Scheme one group stack idea

 var removeDuplicates = function (s) {
    let stack = [] // 1. 创建一个栈数组,用于存放数据
    for (let i = 0; i < s.length; i++) { // 2. 遍历字符串执行入栈出栈操作
        // 3. 一开始栈是空的,所以不用看if,直接看else的操作
        if (stack.at(-1) === s[i]) { // 5. 若栈中已有的顶部数据项(最后一项)和即将要入栈的数据一致,就说明是重复项了
            stack.pop() // 6. 重复项的话,就删除呗(即将入栈的这一项忽略,同时把栈顶部数据即最后一项删除)
        } 
        // 4. 新来的这一项,入栈(尾部追加)
        else {
            stack.push(s[i]) // 栈是特殊的数组,只会用到尾部增push、尾部删pop
        }
    }
    // 7. 最后栈中存放的数据就是不相邻重复的数据
    return stack.join('') // 8. 然后把栈数组转成字符串返回出来即可
};

There are many applications of stack, but if you encounter the problem of "成对" , you can consider using 栈的思想 to solve it. That is, 尾部增、尾部删。

So, this question can also be used 字符串进行“栈”的操作 , anyway, the tail is added and the tail is deleted.

  • Increment at the end of the string, consider: str = str + 'newStr'
  • Delete the end of the string, consider: str = str.slice(0,-1)
Delete the last item of the string, that is, the 0th to the penultimate item of the reserved string for interception. Note: The slice method intercepts two parameters of the string, and does not include the last item when intercepting, so it is str = str.slice(0,-1)

Therefore, there is the following solution:

Scheme 2 String stack idea

 var removeDuplicates = function (s) {
    let str = '' // 和上方基本一样,只不过由数组栈换成了字符串了。故不赘述了
    for (let i = 0; i < s.length; i++) {
        if (str.at(-1) == s[i]) {
            str = str.slice(0, -1) // 尾部删
        } else {
            str = str + s[i] // 尾部增
        }
    }
    return str
};

Summarize

当遇到成对出现的问题时候,考虑使用栈的思想去操作...

Because the tail addition and tail deletion can just be operated in pairs


水冗水孚
1.1k 声望589 粉丝

每一个不曾起舞的日子,都是对生命的辜负