Why we need those codes? and what is used for?


  • 0
    Z

    Would you please help to explain the usage of below code? Why we need to remove the char from hashset? Thanks
    a lot!

     if (set.contains(s.charAt(i))) {
            while (leftBound < i && s.charAt(leftBound) != s.charAt(i)) {
                set.remove(s.charAt(leftBound));
                leftBound ++;
            }
            leftBound ++;
        }
    

    Below is the entire code:

    public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        HashSet<Character> set = new HashSet<Character>();
        
        int leftBound = 0, max = 0;
        for (int i = 0; i < s.length(); i++) {
            if (set.contains(s.charAt(i))) {
                while (leftBound < i && s.charAt(leftBound) != s.charAt(i)) {
                    set.remove(s.charAt(leftBound));
                    leftBound ++;
                }
                leftBound ++;
            } else {
                set.add(s.charAt(i));
                max = Math.max(max, i - leftBound + 1);
            }
        }
        
        return max;
    }
    

    }


  • 0
    C

    Because every time when a new char comes in, we just need to keep the non-dup substring from current index i to leftbound. The result is not able to include dup characters. So when new character comes in,if it is already in our substring, we need to find the position of the character and delete all the characters in the left of the position.

    For example: abcdb. We start from a, when we get d, now the substring is abcd. When the 2nd "b" comes in, we find the previous "b"'s position is 2, so we keep track of the new valid substring which is cdb. We need to delete all the characters in the left of position 2.


Log in to reply
 

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