C language learning: the longest substring of a string without repeated characters

description

Given a string, please find out the length of the longest substring that does not contain repeated characters.

Example

Input: "abcabcbb"

Output: 3

Explanation: Because the longest substring without repeated characters is "abc", its length is 3.

Input: "bbbbb"

Output: 1

Explanation: Because the longest substring without repeated characters is "b", its length is 1.

Input: "pwwkew"

Output: 3

Explanation: Because the longest substring without repeated characters is "wke", its length is 3.

     Please note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring.

Code:

int lengthOfLongestSubstring(char * s){

}

 int max(int a,int b){

   return a>b?a:b;

 }

 int lengthOfLongestSubstring(char * s){

     int len=strlen(s);

    if(len<2)return len;

    int m=1,ch=s[0],p=0;

    for(int i=1;i<len;i++){

        for(int j=p;j<i;j++){

          if(s[j]==s[i]){

              m=max(m,i-p);

                p=j+1;

          }

         }

    }

    m=max(m,len-p);

     return m;

}

It is necessary to consider various situations carefully, such as empty strings, no repetition of characters, and so on.

Hashing will be faster.

Below is the code that others use hashing

 int lengthOfLongestSubstring(char * s){

 int start = 0, end = 0, maxlen = 0;

   char map[256] = {0};

    map[(int)*(s+start)] = 1;

    while( *(s+end) != 0 )

    {

         maxlen = maxlen>(end-start+1)?maxlen:(end-start+1);

       ++end;

        while( 0 != map[ (int)*(s+end) ] )//将要加入的新元素与map内元素冲突

      {

          map[ (int)*(s+start) ] = 0;

             ++start;

      }

        map[(int)*(s+end)] = 1;

    }

    return maxlen;

 }


In addition, if you want to better improve your programming ability, learn C language and C++ programming! Overtaking in a curve, one step faster! I may be able to help you here~

UP has uploaded some video tutorials on learning C/C++ programming on the homepage. Those who are interested or are learning must go and take a look! It will be helpful to you~

Sharing (source code, actual project video, project notes, basic introductory tutorial)

Welcome partners who change careers and learn programming, use more information to learn and grow faster than thinking about it yourself!

Programming learning:

Programming learning:

 

Guess you like

Origin blog.csdn.net/weixin_45713725/article/details/115176531