My Java Solution O(N)


  • 0
    A
    hopefully this helps. 
    
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s.length()<=1) return s.length();
            int[] table = new int[256];
            int slow=0;
            int fast=1;
            table[s.charAt(slow)]=1;
            int max=0;
            while(fast<s.length()){
                if(table[s.charAt(fast)]==1){
                    slow++;
                    table[s.charAt(slow-1)]=0;
                }
                else{
                    fast++;
                    table[s.charAt(fast-1)]=1;
                }
                if(max<fast-slow) max=fast-slow;
            }
            return max;
        }
    }
    

    I was going to use a hashtable then realized I don't need it. Realized I could use a Boolean array instead


Log in to reply
 

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