2019-05-15_16-lengthOfLongestSubstring

  • string
  • array
  • map

first trial:

var lengthOfLongestSubstring = function(s) {
    // console.log(s.split(''))
    let sArr = s.split('');
    let map = {};
    let tempRes = 0;
    let res = 0;

    let tempCount = 0;

    for (let i = 0; i < sArr.length; i++) {
        const char = sArr[i];

        // if map contain the char
        if(map[char] !== undefined){
            tempCount = deletePropBeforIndex(map, map[char], tempCount);
            map[char] = i;
            tempCount++;
        }else{
            map[char] = i;
            tempCount++;
            tempRes = tempCount;

            // test example: 'nfpdmpi'
            // tempRes if updated when map length changed
            // res is stored the bigest value   
            if(tempRes > res) res = tempRes;
        }
        
    }

    return res;
}

deletePropBeforIndex = (obj,index, tempCount)=>{
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            let value = obj[key];
            if(value <= index){
                delete obj[key]
                tempCount--
            }
        }
    }

    return tempCount;
}

console.log(lengthOfLongestSubstring("nfpdmpi"));

// Runtime: 340 ms, faster than 21.84% of JavaScript online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 42.5 MB, less than 19.99% of JavaScript online submissions for Longest Substring Without Repeating Characters.
// From 10:30 - 12: 21

second trial
05-16
09:00 - 10:00 on bus
21:00 - 21:15 at home

// Given a string, find the length of the longest substring 
// without repeating characters.
var lengthOfLongestSubstring = function (s) {
    var sArr = s.split('');
    // at most, res = aArr.length
    var arr = [];
    var res = 0;
    var tempLength = 0;
    for (var i = 0; i < sArr.length; i++) {
        var value = sArr[i];
        var dIndex = arr.indexOf(value);
        // arr contains the value
        if (dIndex >= 0) {
            // delete the subArr from 0 to dIndex
            arr = arr.slice(dIndex + 1, arr.length);
            arr.push(value);
            tempLength = arr.length;
        }
        else {
            arr.push(value);
            tempLength = arr.length;
            res = Math.max(tempLength, res);
        }
    }
    return res;
};

// console.log(lengthOfLongestSubstring("aab"));


// Runtime: 96 ms, faster than 84.26% of JavaScript online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 42 MB, less than 27.72% of JavaScript online submissions for Longest Substring Without Repeating Characters.

refactored

// Given a string, find the length of the longest substring 
// without repeating characters.
var lengthOfLongestSubstring = function (s) {
    var sArr = s.split('');
    var arr = [];
    var res = 0;
    var tempLength = 0;
    
    for (var i = 0; i < sArr.length; i++) {
        var value = sArr[i];
        // the duplication value index
        var dIndex = arr.indexOf(value);
        // if the arr contains the value
        if (dIndex >= 0) {
            // delete the subArr from 0 to dIndex
            // slice function has no side effect
            arr = arr.slice(dIndex + 1, arr.length);
            // remember to push the new value to arr
            // failed in here in thinking, got it through step debug
        }
        
        // all need to push the new value
        arr.push(value);
        tempLength = arr.length;
        
        // update the biggest to res
        res = Math.max(tempLength, res);
    }
    return res;
};

// console.log(lengthOfLongestSubstring("aab"));


Runtime: 76 ms, faster than 99.64% of JavaScript online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 41.6 MB, less than 39.30% of JavaScript online submissions for Longest Substring Without Repeating Characters.

conclusion

  • use a store(arr vs map) to store scanned value O(1) - O(1)
  • if a new value existed in the store n* O(n) - n*O(1)
var lengthOfLongestSubstring = function(s) {
    if (s.length <= 1) return s.length;
    
    s = s.split('');
    let seen = {};
    let sub = '';
    let largestSub = '';
    
    for (let i = 0; i < s.length; i++) {
        seen[s[i]] = seen[s[i]] + 1 || 1;
        
        if (seen[s[i]] > 1) {
            sub = sub.substring(sub.indexOf(s[i]) + 1);
        }
        sub += s[i];
        
        if (sub.length > largestSub.length) {
            largestSub = sub;
        }
        
    }
    
    return largestSub.length;
};
/**
 * could also split at every letter and check the lengths of each...
 */
function lengthOfLongestSubstring(x) {
  // console.group(`${x}`)
  const list = x.split('')
  /**
   * @type {string[]}
   */
  let current = []
  let longest = 0

  for (let index = 0; index < list.length; index++) {
    const value = list[index]
    // console.info(current.join(',') || '[]', ';', index, value)

    if (current.includes(value)) {
      // console.log('resetting')

      // if it's the last one...
      const lastIndexOfValue = current.indexOf(value)
      const length = current.length
      const isLast = lastIndexOfValue === length - 1

      // update
      const everythingAfter = current.slice(lastIndexOfValue + 1, length)
      const merged = [...everythingAfter, value]

      // console.log(`
      // length: ${length},
      // lastIndexOfValue: ${lastIndexOfValue + 1},
      // current: ${current.join(',') || '[]'},
      // everythingAfter: ${everythingAfter.join(',') || '[]'},
      // merged: ${merged.join(',') || '[]'},
      // isLast: ${isLast},
      //       `)

      current = isLast === true ? [value] : merged
    } else {
      // console.log('adding')
      current.push(value)
    }

    if (current.length > longest) {
      longest = current.length
    }

    // console.log('\n')
  }

  // console.log(current)
  // console.log(longest)
  // console.groupEnd()

  return longest
}

// function test() {
//   console.assert(lengthOfLongestSubstring('pwwkew') === 3, 'pwwkew')
//   console.assert(lengthOfLongestSubstring('bbbbb') === 1, 'bbbbb')
//   console.assert(lengthOfLongestSubstring('abc') === 3, 'abc')
//   console.assert(lengthOfLongestSubstring('aab') === 2, 'aab')
//   console.assert(lengthOfLongestSubstring('dvdf') === 3, 'dvdf')
//   console.assert(lengthOfLongestSubstring('aabaab!bb') === 3, 'aabaab!bb')
/**
 * @param {string} s
 * @return {number}
 */

var lengthOfLongestSubstring = function (s) {
 let res = s.split('').reduce(
        (pre, cur) => {
        let st = pre[0].indexOf(cur);
            if (st > -1) {
                return [
                    pre[0].slice(st + 1) + cur,
                    Math.max(pre[0].length, pre[1])
                ];
            } else {
                return [
                    pre[0] + cur,
                    pre[1]
                ];
            }

        }, ['', 0]
    );
    return Math.max(res[0].length, res[1]);
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末稻爬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子穴吹,更是在濱河造成了極大的恐慌,老刑警劉巖应媚,帶你破解...
    沈念sama閱讀 206,602評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件规肴,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡胯府,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,442評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)腌乡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)盟劫,“玉大人夜牡,你說(shuō)我怎么就攤上這事与纽。” “怎么了塘装?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,878評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵急迂,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我蹦肴,道長(zhǎng)僚碎,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,306評(píng)論 1 279
  • 正文 為了忘掉前任阴幌,我火速辦了婚禮勺阐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘矛双。我一直安慰自己渊抽,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,330評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布议忽。 她就那樣靜靜地躺著懒闷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪栈幸。 梳的紋絲不亂的頭發(fā)上愤估,一...
    開(kāi)封第一講書(shū)人閱讀 49,071評(píng)論 1 285
  • 那天,我揣著相機(jī)與錄音速址,去河邊找鬼玩焰。 笑死,一個(gè)胖子當(dāng)著我的面吹牛芍锚,可吹牛的內(nèi)容都是我干的昔园。 我是一名探鬼主播荔棉,決...
    沈念sama閱讀 38,382評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼蒿赢!你這毒婦竟也來(lái)了润樱?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,006評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤羡棵,失蹤者是張志新(化名)和其女友劉穎壹若,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體皂冰,經(jīng)...
    沈念sama閱讀 43,512評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡店展,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,965評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了秃流。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赂蕴。...
    茶點(diǎn)故事閱讀 38,094評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖舶胀,靈堂內(nèi)的尸體忽然破棺而出概说,到底是詐尸還是另有隱情,我是刑警寧澤嚣伐,帶...
    沈念sama閱讀 33,732評(píng)論 4 323
  • 正文 年R本政府宣布糖赔,位于F島的核電站,受9級(jí)特大地震影響轩端,放射性物質(zhì)發(fā)生泄漏放典。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,283評(píng)論 3 307
  • 文/蒙蒙 一基茵、第九天 我趴在偏房一處隱蔽的房頂上張望奋构。 院中可真熱鬧,春花似錦拱层、人聲如沸弥臼。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,286評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)醋火。三九已至,卻和暖如春箱吕,著一層夾襖步出監(jiān)牢的瞬間芥驳,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,512評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工茬高, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留兆旬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,536評(píng)論 2 354
  • 正文 我出身青樓怎栽,卻偏偏與公主長(zhǎng)得像丽猬,于是被迫代替她去往敵國(guó)和親宿饱。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,828評(píng)論 2 345