Created
March 15, 2013 04:55
-
-
Save linzhp/5167588 to your computer and use it in GitHub Desktop.
http://leetcode.com/onlinejudge#question_3 http://leetcode.com/2011/05/longest-substring-without-repeating-characters.html
This file contains 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
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