Last active
October 7, 2018 09:21
-
-
Save hsaputra/dbeada3d906115610c510889bd287e63 to your computer and use it in GitHub Desktop.
Longest Substring Without Repeating Characters - https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int lengthOfLongestSubstring(String s) { | |
// check for invalid arguments. | |
if (s == null || s.length() == 0) { | |
return 0; | |
} | |
if (s.length() == 1) { | |
return 1; | |
} | |
// DO Windowing | |
int i = 0; int j = 0; | |
int count = 0; | |
// Loop until both pointers gone | |
final int sLen = s.length(); | |
// Use Set to check duplicate | |
Set<Character> setDuplicate = new HashSet<Character>(); | |
int countMax = 0; | |
while (i < sLen && j < sLen) { | |
// If we hav not seen it, then add count and move up j | |
char curVal = s.charAt(j); | |
if (!setDuplicate.contains(curVal)) { | |
j++; | |
setDuplicate.add(curVal); | |
countMax = Math.max(countMax, j - i); | |
} | |
// Else remove from set and move up i | |
else { | |
char removedFirst = s.charAt(i); | |
setDuplicate.remove(removedFirst); | |
i++; | |
} | |
} | |
return countMax; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With Map: