Topic Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Topic:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "ABCABCBB", the answer is "ABC" and which the length is 3.
Given "BBBBB", the answer is ' B ', with the length of 1.
Given "Pwwkew", the answer is ' Wke ', with the length of 3. Note that the answer must to be a substring, "Pwke" are a subsequence and not a substring.
Analytical:
Use HashMap to store not repeating substrings, key is a character, value is the position of this character. Traversing backwards, as long as there is no current character in the map, it is added to the map. and add the substring length to one. If the current character already appears in the map, get the position of this character in the map, clear this position and all keys before it. The substring is recalculated after this position, ensuring that the substring is not duplicated.
Java code implementation:
public class Solution {
public int lengthoflongestsubstring (String s) {
if (s = = null) return 0;
Hashmap<character, integer> map = new Hashmap<character, integer> ();
int start = 0;
int maxlen = 0;
int len = 0;
for (int i = 0; i < s.length (); i++) {
if (!map.containskey (S.charat (i))) {
len++;
if (Len > maxlen) maxlen = len;
Map.put (S.charat (i), i);
}else{
int index = Map.get (S.charat (i));
for (int j = start; J <= Index; j +) {
Map.Remove (S.charat (j));
}
Map.put (S.charat (i), i);
start = index+1;
len = I-index;
}
}
return maxlen;
}
}