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

时间:2022-12-23 22:18:34

Given a string, find the length of the longest serial 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.

 

题目解析:意思就是找出字符串的连续递增 or 递减子串,返回该串及其长度

 

思路:

1 用另一个数组存储每一个char的“状态”;

2 正数表示递增,0表示与前一个char相同不增不减,负数表示递减;

3 如+3表示该char是第4个递增字符(从0开始);

4 如字符串"dkggashgt"对应的状态数组如下:

     0,1,-1,0,-1,1,-1,-2,1

   记录最大 or 最小值,即为最长递增 or 最长递减串长度,对应数组下标亦为最长串最后char的数组下标;

 

代码是js写的,如下:

 1 var lengthOfLongestSubstring = function(str) {
 2     if(str.length === 0) return 0;
 3     var maxLen = 1; //maximum serial string length
 4     var maxIdx = 0; //the array sub-index of the last char in the result string 
 5     var tmpArr = [0]; //array to save the status data
 6     for (var i = 1, len = str.length; i < len; i++) {
 7         var pa = str[i-1];
 8         var pb = str[i];
 9         var ra = tmpArr[i-1];
10         if(pa>pb){
11             if(ra<0){
12                 tmpArr.push(ra-1);
13                 if(-1*tmpArr[i]+1 > maxLen){
14                     maxLen = -1*tmpArr[i]+1;
15                     maxIdx = i;
16                 }
17 
18             }else{
19                 tmpArr.push(-1);
20                 if(maxLen<2){
21                     maxLen = 2;
22                     maxIdx = i;
23                 }
24             }
25         }else if(pa<pb){
26             if(ra>0){
27                 tmpArr.push(ra+1);
28                 if(tmpArr[i]+1 > maxLen){
29                     maxLen = tmpArr[i] + 1;
30                     maxIdx = i;
31                 }
32             }else{
33                 tmpArr.push(1);
34                 if(maxLen<2){
35                     maxLen = 2;
36                     maxIdx = i;
37                 }
38             }
39         }else{
40             tmpArr.push(0);
41         }
42     }
43     var strRet = str.slice(maxIdx-maxLen+1, maxIdx+1);//result string
44     return [strRet,maxLen]; //result string and its length
45 };