Thursday, January 7, 2021

LeetCode: Longest Substring Without Repeating Characters

 The problem statement is copy pasted from leetcode as it is:

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

 

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:

Input: s = ""
Output: 0

 

Constraints:

  • 0 <= s.length <= 5 * 104
  • s consists of English letters, digits, symbols and spaces.

My solution:

package madwani.sushil.leetcode.Amazon;

import java.util.*;

public class LongestSubstringWithoutRepeatingCharacters {
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring6("daabcdefabcffg"));
System.out.println(lengthOfLongestSubstring6("abcabcbb"));
System.out.println(lengthOfLongestSubstring6("bbbbb"));
System.out.println(lengthOfLongestSubstring6("pwwkew"));
System.out.println(lengthOfLongestSubstring6(" abccbaddeabcde"));
System.out.println(lengthOfLongestSubstring6(" abcdeafbdgcbb"));
System.out.println(lengthOfLongestSubstring6(" abc__fbdg_bb"));
}
// we will solve using sliding window method
public static int lengthOfLongestSubstring6(String s) {
if ( s == null ) {
return 0;
}
// windows start index and end index
int start_index = 0, end_index = 0;

// current window size
int window_size = 0;

// to track different characters
Set<Character> uniqueChars = new HashSet<>();
while ( end_index < s.length()) {
if (!uniqueChars.add(s.charAt(end_index))) {
// if not able to add, means duplicate character
// remove the start_index char
uniqueChars.remove(s.charAt(start_index));
// and move the start_index till the duplicate character is not removed
start_index++;
} else {
// unique character added to window
// if window_size is increased
window_size = Math.max(uniqueChars.size(), window_size);
// move the window further
end_index++;
}
}
return window_size;
}
}

No comments: