No repeated character calculated longest substring

Topics requirements: Given a string, you find out which does not contain a repeated character  longest substring  length.

Test test case contains:

Example 1:

Input: "abcabcbb"
Output: 3
Explanation: Because the longest substring of characters without repetition is "abc", so its length is 3.

Example 2:

Input: "bbbbb"
Output: 1
Explanation: Because the longest substring is repeated characters without "b", so that its length is 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: Because the longest substring is repeated characters without "wke", so its length is 3.
     Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.

 

I submit verification code is as follows:

The code for the C language version

int lengthOfLongestSubstring(char * s){
    int i;
    int max = 0;
    int  left =  0 ; // left border of the window
    int table[256]; 
    int tmp=0;
  int len ​​= strlen (s);
    for(i=0;i<256;i++){
        table[i]=-1;
   }

    for (I =  0 ; I <len; I ++) {// the control window on the right of the boundary
        int index = s[i];
        IF (left <= Table [index] && Table [index] <= I) {// determines whether the occurrence of repeated characters
                = Table left [index] + . 1 ; // Update the left window boundary value
        }
        I = left-+ tmp . 1 ; // calculate the current size of the sliding window
        ? Max = tmp> max tmp: max; // updates the maximum length of the substring
        table [index] = i; // record the current character in the string index
    }
    return max;
}
Problem solution ideas:
  In the title main use of the concept of sliding window, for the first string, we need to do is to find the maximum length of the substring by a traversal, enabling time complexity is O (N) algorithm to achieve,
在此过程中,将字符串的起始位置设为滑动窗口的左边界,I值作为滑动窗口的右边界,I也就是字符串的下标,在遍历的过程中,我们将当前字符对应的ASCII码
作为了table中的index值,其中的table相当于一个哈希表,每一个元素的value,就是这个字符在字符串中的下标位置,在遍历的时候,每遍历一个字符,我们
都需要计算当前的窗口大小,然后拿当前窗口大小与max值做比较,进行更新,现在问题的关键是,如何控制滑动串口左边界的值,因为滑动窗口的右边界是实时变化的
随着I的增加,可以看到,当发现当前字符在table中对应的值,在窗口之间的时候,就可以判断,发生了字符的重复,需要去更新滑动窗口的左值,那么如何更新呢?
直接将发生碰撞的那个字符在table中的value取出,然后,将value+1赋给left,就是新的左边窗口大小了;在遍历的时候,只要将右边界减去左边界加1就可以计算出当前
窗口大小,然后对最大子串的长度进行更新。
遇到的问题:
1:比较弱智的是,当前在对int型的数组进行初始化的时候,写的是 int table[256]={-1},想要初始化为-1,只能for循环对于C语言而言;


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

Guess you like

Origin www.cnblogs.com/pigdragon/p/12393029.html