数组算法 3
Posted slardarr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组算法 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的主要内容,如果未能解决你的问题,请参考以下文章