Ruby's Louvre

每天学习一点点算法

导航

leetcode 844. Backspace String Compare

比较两个带退格键的字符串

方法1, 从后往前遍历,记录要忽略掉的字符

var backspaceCompare = function(S, T) {
    return getMormalString(S) === getMormalString(T)
};

function getMormalString(S){
     var eat = 0, sb = []
     for(var i = S.length-1; i>=0 ; i--){
         if(S[i] == '#'){
             eat++
         }else{
             if(eat > 0){
                 eat--
             }else{
                 sb.push(S[i])
             }
         }
     }
    return sb.join('')
}

方法2, 使用栈,从前往后处理

var backspaceCompare = function(S, T) {
     if (!S || !T || S.length === 0 || T.length === 0) {
        return false;
    }
    
    let stackS = [];
    let stackT = [];
    
    for (let i = 0; i < S.length; i++) {
        if (S[i] !== '#') {
            stackS.push(S[i]);
        } else {
            stackS.pop();
        }
    }
    
    for (let i = 0; i < T.length; i++) {
        if (T[i] !== '#') {
            stackT.push(T[i]);
        } else {
            stackT.pop();
        }
    }
    
    if (stackS.length !== stackT.length) {
        return false;
    } else {
        for (let i = 0; i < stackS.length; i++) {
            if (stackS[i] !== stackT[i]) {
                return false;
            }
        }
    }
    return true;
}

方法3,使用归并排序合并数组的形态,从后往前比较

var backspaceCompare = function(S, T) {
    let sPointer = S.length - 1;
    let tPointer = T.length - 1;
    let sBackspaces = 0;
    let tBackspaces = 0;

    while (sPointer >= 0 || tPointer >= 0) {
        if (S[sPointer] === '#') {
            sBackspaces++;
            sPointer--;
            continue;
        }
        
        if (T[tPointer] === '#') {
            tBackspaces++;
            tPointer--;
            continue;
        }
        
        if (sBackspaces > 0) {
            sBackspaces--;
            sPointer--;
            continue
        }

        if (tBackspaces > 0) {
            tBackspaces--;
            tPointer--;
            continue;
        }

        if (S[sPointer] !== T[tPointer]) {
            return false;
        }
        
        sPointer--;
        tPointer--;
    }
    
    return true;
};
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年

posted on 2020-01-02 01:00  司徒正美  阅读(207)  评论(0编辑  收藏  举报