Java solution that uses one Set


  • 3
    D
    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            Set<Character> set = new HashSet<>();
            int p1 = 0;
            int p2 = 0;
            int ret = 1;
            while (p2 < s.length()) {
                while (set.contains(s.charAt(p2))) {
                    set.remove(s.charAt(p1));
                    p1++;
                }
                set.add(s.charAt(p2));
                ret = Math.max(ret, p2 - p1 + 1);
                p2++;
            }
            return ret;
        }
    }
    

  • 0

    Why you remove p1?
    If the test case is: abcb
    When you check b is duplicated, you remove a. So this would be wrong


  • 1
    D

    @Harrywithcode Oh, here is the reason: when you see b, and find out b has appeared before, then no matter whether the previous b is the head of the window, you have to continuously delete the head character until you have deleted the previous b.


  • 0
    S

    Interesting solution, always use 'ret' to save the biggest value.


Log in to reply
 

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