LeetCode #3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

 

以“pwwkew”作为参考

var s = "pwwkew";
    var arr = [];
    var repeatArr = [];
    var resultArr=[];
    //Step1:splice String into all the possible substrings
    for (var i = 0; i < s.length; i++) {
        for (var j = s.length; j >i; j--) {
            arr.push(s.substring(i, j));
        }
    }
    console.log(arr);//["p", "pw", "pww", "pwwk", "pwwke", "w", "ww", "wwk", "wwke", "w", "wk", "wke", "k", "ke", "e"]
    //Step2:Find out all the string that contains repeated letters;
    for (var m = 0; m < arr.length; m++) {
        for (var p = 0; p < arr[m].length; p++) {
            for (var q = arr[m].length - 1; q > p; q--) {
                if (arr[m].charAt(p) !== arr[m].charAt(q)) {
                    console.log("not repeat letters")
                } else if (arr[m].charAt(p) == arr[m].charAt(q)) {
                    repeatArr.push(arr[m]);
                }
            }
        }
    }
    console.log(repeatArr);//["pww", "pwwk", "pwwke", "ww", "wwk", "wwke"]
    //Step3:Remove the Strings in Step2 from Step1
    for(var k=0;k<arr.length;k++){
        var everyResult=repeatArr.every(function(item,index,array){
          return arr[k]!=item;
        });
        if(everyResult){
            resultArr.push(arr[k]);
        }
    }
    console.log(resultArr)//["p", "pw", "w", "w", "wk", "wke", "k", "ke", "e"]
    //Step4.Just find out the longest word in resultArr
    var longestNorepeatWord="";
    var wordlength=0;
    for(var x=0;x<resultArr.length;x++){
        if(resultArr[x].length>wordlength){
            longestNorepeatWord=resultArr[x];
            wordlength=resultArr[x].length;
        }
    }
    console.log(longestNorepeatWord);//wke

  感觉好蠢 这么白痴的循环,肯定有简单的方法,不管怎样把这结果撸出来了 nnd

 

posted on 2016-09-08 11:14  carlyin  阅读(137)  评论(0)    收藏  举报

导航