longest-substring-without-duplicate-characters

public class LengthOfLongestSubstring {
public static int lengthOfLongestSubstring(String s) {
if (s == null) {
return 0;
}
Map<Character, Integer> map = new HashMap<>();
int maxLength = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
Integer duplicateIndex = map.put(c, i);
if (duplicateIndex != null) {
if (duplicateIndex >= start) {
maxLength = Math.max(maxLength, i - start);
start = duplicateIndex + 1;
}
}
}
return Math.max(maxLength, s.length() - start);
}

public static void main(String[] args) {
int maxLength = lengthOfLongestSubstring("abcabcbb"); // 3
System.out.println(maxLength);

maxLength = lengthOfLongestSubstring("bbbbb"); // 1
System.out.println(maxLength);

maxLength = lengthOfLongestSubstring("b"); // 1
System.out.println(maxLength);

maxLength = lengthOfLongestSubstring(""); // 0
System.out.println(maxLength);

maxLength = lengthOfLongestSubstring(null); // 0
System.out.println(maxLength);
}
}

About Hieu Nguyen

I am a Senior member of technical staff (Oracle, eBay, Microsoft) and a founder of iNest, LLC (an IoT company)
This entry was posted in hashtable. Bookmark the permalink.