Software engineer

LC-Longest Substring Without Repeating Characters

LC-Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

Question

Given a string s, find the length of the longest substring without repeating characters.

Input: s = “abcabcbb”

Output: 3

Explanation: The answer is “abc”, with the length of 3.

class Solution {
  public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    int ans = 0;
    int left = 0, right = 0;
    HashSet<Character> set = new HashSet<>();
    while (left < n && right < n) {
      if (!set.contains(s.charAt(right))) {
        set.add(s.charAt(right++));
        ans = Math.max(ans, right - left);
      } else {
        set.remove(s.charAt(left++));
      }
    }
    return ans;


  }
}
comments powered by Disqus