Last active
December 14, 2015 22:39
-
-
Save daifu/5159928 to your computer and use it in GitHub Desktop.
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
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
| import java.util.*; | |
| public class Solution { | |
| public int lengthOfLongestSubstring(String s) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| int count = 0; | |
| int max = 0; | |
| int startIndex = 0; | |
| int endIndex = 0; | |
| HashMap<Character, Integer> table = new HashMap<Character, Integer>(); | |
| int size = s.length(); | |
| for(int i = 0; i < size; i++) { | |
| if(!table.containsKey(s.charAt(i))) { | |
| count++; | |
| table.put(s.charAt(i), i); | |
| } else { | |
| if (count > max) { | |
| max = count; | |
| } | |
| // deal with the case for axefgxhi when x is duliplicated. | |
| endIndex = table.get(s.charAt(i)); | |
| for(int j = endIndex; j >= startIndex; j--) { | |
| table.remove(s.charAt(j)); | |
| count--; | |
| } | |
| table.put(s.charAt(i), i); | |
| count++; | |
| startIndex = endIndex + 1; | |
| } | |
| } | |
| if (count > max) { | |
| max = count; | |
| } | |
| return max; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment