Why am I getting time limit exceeded?


  • 0
    Y

    Here is my code for this prrblem -

    if (s == null || s.length() == 0) return 0;
            HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
            char[] arr = s.toCharArray();
            hm.put(arr[0], 1);
            int start = 0, i = 1, max = 1;
            while (i < s.length()){
                if (hm.get(arr[i]) == null) {
                    hm.put(arr[i], i);
                }
                else { 
                    if (max <  i-start)
                        max = i - start;
                    start = hm.get(arr[i]) + 1;
                    i = start;
                    hm.clear();
                    hm.put(arr[i], i);
                }
                i++;
            }
            if (max < i-start)
                max = i - start;
            return max;
    

    I even checked the solution given here. But I am unable to understand why my solution does not work. It is giving me the right answers on eclipse. Is it because I am using the clear method of HashMap? Does that take a lot of time?


  • 0
    R

    why u r using hashmap?
    a simple char buff[256] will do.

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int arr[256]={0};
            int k = s.length();
            int start=0,count=0,max=0,i;
            for(i=0;i<s.length();i++)
            {  
                if(arr[s[i]]&&arr[s[i]]>=start )
                {
                    start=arr[s[i]];
                    count=i-start+1;
                    arr[s[i]]=i+1;
                }
    
                else
                {
                    arr[s[i]]=i+1;
                    ++count;
                }
    
    
              if(count>max)
                 max=count;
    
      }
            return max;
        }
    };

Log in to reply
 

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