Java Two Pointers AC without using Map


  • 0
    O

    Using two pointers Slow & Fast
    One operation per iteration so it's easy to control what happened every iteration

    public int lengthOfLongestSubstring(String s) {
            
            boolean[] chars = new boolean[256];
            int slow = 0, fast = 0, res = 0;
            
            //Slide window
            while (fast<s.length()) {
                if (!chars[s.charAt(fast)]) {
                    chars[s.charAt(fast)] = true;
                    fast++;
                    res = Math.max(res, fast-slow);
                }
                else {
                    chars[s.charAt(slow)] = false;
                    slow++;
                }
            }
    
            return res;
    }
    

Log in to reply
 

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