No repeated character LeetCode02- longest substring

Title Description

Here Insert Picture Description

The basic idea

Sliding window

  • Use HashSetto achieve
  • Use HashMapto achieve

Java implementation

  • HashSet
    public static int lengthOfLongestSubstring3(String s) {
        if(s == null || s.length() == 0) return  0;

        HashSet<Character> set = new HashSet<>();
        int res = 0;
        for(int i = 0, j = 0; i < s.length(); i ++ ) {
            if(set.contains(s.charAt(i))) {
                set.remove(s.charAt(j));
                j++;
                i--;
            } else {
                set.add(s.charAt(i));
                res = Math.max(res, i - j + 1);
            }
        }
        return res;
     }
  • HashMap
    public static int lengthOfLongestSubstring2(String s) {
        if( s == null || s.length() == 0) return 0;
        HashSet<Character> set = new HashSet<>();
        int res = 0;
        for(int i = 0, j = 0; i < s.length(); i++) {
            if(set.contains(s.charAt(i))) {
                set.remove(s.charAt(j));
                j++;
            } else {
                set.add(s.charAt(i));
                res = Math.max(res, i - j + 1);
            }
        }
        return res;
    }

Published 32 original articles · won praise 7 · views 7578

Guess you like

Origin blog.csdn.net/Isaacddx/article/details/87881689