Optimize my C++ solution(20ms)?


  • 0
    J
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            const int ASCII_MAX=26;
            int last[ASCII_MAX];
            int start=0;
            fill(last,last+ASCII_MAX,-1);
            int max_len=0;
            for(int i=0;i<s.size();i++){
                if(last[s[i]-'a']>=start){
                    max_len=max(i-start,max_len);
                    start=last[s[i]-'a']+1;
                }
                last[s[i]-'a']=i;
            }
            return max((int)s.size()-start,max_len);
        }
    };
    

    Are the letters restricted to 'a'~'z'?


  • 0
    J

    I get it.it's more than 26 english letters.And s[i]-'a' is not right.So I just simply remove the minus,just s[i].And change ASCII_MAX into 256.At last,Answer is Accepted.
    The runtime is 20ms.


Log in to reply
 

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