leetcode 925. Long Pressed Name


判定是否長按

var isLongPressedName = function (name, typed) {
            var i = 1, j = 0, n = name.length, m = typed.length;
            var last = name[0], iCount = 1
            while (i < n || j < m) {
                var el = name[i];
                if (el !== last) {
                    if (iCount !== 0) {
                        let jCount = 0
                        // console.log("j", j, m)
                        while (j < m) {
                            console.log("內循環", last, typed[j], j)
                            if (typed[j] !== last) {
                                break //跳到外循環
                            }
                            j++
                            jCount++
                        }

                        if (jCount < iCount) {
                            return false
                        }
                        if (j == m && i < n) {
                            return false
                        }
                    }
                    last = el
                    iCount = 1
                } else {
                    console.log("累加", el)
                    iCount++
                }
                i++
            }
            return true

        };

        console.log(isLongPressedName("alex", "aaleex"))
        console.log(isLongPressedName("saeed", "ssaaedd"))
        console.log(isLongPressedName("pyplrz", "ppyypllr"))

更精簡的實現

var isLongPressedName = function(name, typed) {
    let j = 0;
    
    for (let i = 0; i < typed.length; i++) {
        if(name[j] == typed[i]) j++;
    }
    
    return j == name.length;
};

另一個

var isLongPressedName = function (name, typed) {
       let nlen = name.length, tlen = typed.length;
        if (nlen > tlen) return false;
        
        let i = 0, j = 0;
        while (i < nlen && j < tlen) {
            let  nc = name.charAt(i);
            let  tc = typed.charAt(j);
            if (nc == tc) {
                i++;
                j++;
            } else {
                if (j == 0 || tc != typed.charAt(j - 1)) {
                    return false;
                }
                j++;
            }
        }
        
        return i == nlen;
 
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM