首页 > 代码库 > 数组算法 3

数组算法 3

/* 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.
 * <<===================================================================================>>
 * @param {string} s
 * @return {number}
 */
function lengthOfLongestSubstring(string) {
  var s = string.toString();
  var stringArray = [];
  var result = 0;
  // 将字符串转换为数组
  for( var k = 0; k < s.length; k ++ ){
    stringArray.push(s[k]);
  } 
  var len = stringArray.length;
  //  判断是否为无重数组
  var ok = stringArray.length == Array.from(new Set(stringArray)).length ? true : false;
  // 判断数组中是否存在某元素
  function arr( arr, val ){
    var tof = false;
    for(var i = 0; i < arr.length; i++ ){
      if( arr[i] == val ) {
        tof = true;
      }
    }
    return tof;
  }
  // 获取字符串数组最大长度
  function getLen( stringarray ){
    var noRepeatArray = [];
    for( var i = 0; i < stringarray.length; i ++ ){
      // 是否可PUSH
      if( !arr( noRepeatArray, stringarray[i] ) ){
        // 是否为临界值
        if( i == stringarray.length -1 ){
          noRepeatArray.push( stringarray[i] );
          if( noRepeatArray.length > result ){
            result = noRepeatArray.length;
            break;
          }else{
            break;
          }
        }else{
          noRepeatArray.push( stringarray[i] );
        }
      }else{
        if( noRepeatArray.length > result ){
          result = noRepeatArray.length;
          break;
        }else{
          break;
        }
      }
    }
    return result
  }
  // 判断是否为单字符串
  // 循环去掉数组第一个元素
  if(stringArray.length == 1){
    result = 1;
  }else{  
    for( var j = 0; j < len; j ++ ){
      getLen(stringArray);
      stringArray.shift();
    } 
  } 
  if( ok ) {
    return s.length
  }else{
    return result
  }
}

 

数组算法 3