Skip to content

Instantly share code, notes, and snippets.

@linzhp
Created March 15, 2013 04:55
Show Gist options
  • Save linzhp/5167588 to your computer and use it in GitHub Desktop.
Save linzhp/5167588 to your computer and use it in GitHub Desktop.
public class Solution {
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
String longest = "";
int i = 0;
while(i < s.length()) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put(s.charAt(i), i);
int j;
char current;
for(j = i + 1; j < s.length(); j++) {
current = s.charAt(j);
if(map.containsKey(current)) {
break;
} else {
map.put(current, j);
}
}
if(j - i > longest.length()) {
longest = s.substring(i, j);
}
if(j == s.length()) {
break;
} else {
i = map.get(s.charAt(j)) + 1;
}
}
return longest.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment