Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Last active October 7, 2018 09:21
Show Gist options
  • Save hsaputra/dbeada3d906115610c510889bd287e63 to your computer and use it in GitHub Desktop.
Save hsaputra/dbeada3d906115610c510889bd287e63 to your computer and use it in GitHub Desktop.
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;
}
}
@hsaputra
Copy link
Author

hsaputra commented Oct 7, 2018

With Map:

class Solution {
    public int lengthOfLongestSubstring(String s) {
      /**
       * Tests:
       *   Null s
       *   Empty s
       */
      if (s == null || s.length() == 0) {
        return 0;
      }
      
      final int sLen = s.length();
      
      // create a window that measure the longest subset w/o repeat.
      // use the map to check.
      int i = 0;
      int j = 0;
      int maxSoFar = 0;
      Map<Character, Integer> map = new HashMap<Character, Integer>();
      
      while(i < sLen && j < sLen) {
        if (map.containsKey(s.charAt(j))) {
          i = Math.max(map.get(s.charAt(j)) + 1, i); 
        }
        
        map.put(s.charAt(j), j);
        
        //System.out.println("i is " + i);
        //System.out.println("j is " + j);
        //System.out.println("maxSoFar before " + maxSoFar);
        
        maxSoFar = Math.max(maxSoFar, j - i + 1);
        
        //System.out.println("maxSoFar after " + maxSoFar);
        
        j++;
        
        //System.out.println("j after " + j);
      }
      
      return maxSoFar;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment