316. Remove Duplicate Letters

97 阅读1分钟

316. Remove Duplicate Letters

解题思路

1.首先利用 map 统计每个字母出现的最后一次的位置信息

2.遍历循环,首先去重,如果不包含相同的字母

3.其次如果栈顶元素靠后,且后续还有相关字母,那么进行 stack.pop() 出栈

代码

/**
 * @param {string} s
 * @return {string}
 */
/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicateLetters = function (s) {
    // 字母最后出现的位置
    const last = {}
    // 记录需要拼接的字母
    const stack = []
    const len = s.length
    // 'aababc' => {a: 3,b: 4,c: 5}
    for (let i = 0; i < len; i++) {
        last[s[i]] = i
    }
    // 'cbacb'
    // [c]
    // [c,b]
    // a [c,b] 进行两次 pop => ['a']
    // [a,c]
    // [a,c,b]
    const notEmpty = () => stack.length
    const peek = () => stack[stack.length - 1]
    const isBigger = (char) => char < peek()
    const notLast = (i) => last[peek()] > i
    
    for (let i = 0; i < len; i++) {

        if (!stack.includes(s[i])) {
            // 非空 栈顶元素大于 s[i] 且 最后出现的位置大于 i
            while (notEmpty && isBigger(s[i]) && notLast(i)) {
                stack.pop()
            }
            stack.push(s[i])
        }
    }
    return stack.join('')
};