16ms cpp answer,use extra o(n) space.but I can print all these longest characters.


  • 0
    G

    let me to share my code!
    the question ask to find the length of longest substring without repeating char,my code can find all these longest characters and print them if you like.

    struct MaxSite
    {
      int begin;
      int end;
      MaxSite *next;
      MaxSite(int beg,int en):begin(beg),end(en){};
    };
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int length = s.length();
            if(length == 0) return 0;
            int *num = new int[length];
            num[0]=1;
            int i,j,maxlength=1;
            for(i=1;i<length;i++)
            {
                for(j=i-num[i-1];j<i;j++)
                {
                    if(s[j] == s[i]) break;
                }
                if(i==j)num[i] = num[i-1]+1;
                else num[i]=i-j;
                if(num[i] > maxlength) maxlength = num[i];
            }
            // note all longest value
            /*
            MaxSite *max = new MaxSite(-1,-1);
            MaxSite *p;
            p=max;
            for(i=0;i<length;i++)
            {
                if(num[i] == maxlength)
                {
                    p->next = new MaxSite(i-num[i]+1,i); // if you like, you can print them.
                }
            }*/
            delete []num;
            return maxlength;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.