Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer "abc"
is, which the length is 3.
Given "bbbbb"
, the answer "b"
is, with the length of 1.
Given "pwwkew"
, the answer "wke"
is, with the length of 3. Note that the answer must was a substring, is "pwke"
a subsequence and not a substring.
Note: The substring of substring "abc" includes "AB", "BC", "a" and so on, must be continuous, if not continuous as "AC", then called Subsequence (subsequence)
Theme idea: The calculation of a string that does not contain repeating characters is the maximum value for finding the length between two identical characters in a string !
Code:
Package Leetcode;
Import Java.util.HashMap;
Import Java.util.Map;
Import javax.swing.text.AbstractDocument.LeafElement;
Main idea: a non-repeating substring must be surrounded by two identical characters!
Conversion direction: Calculate the length between two identical characters, find the maximum value of the length! is the maximum value of the substring
//
public class Lengthoflongestsubstring {
public static int lengthoflongestsubstring (String s) {
int ret = 0;
int a = 0;
Map<character, integer> map = new hashmap<> (); The bottom layer is an array that expands the list of links (entry), where hashcode and keys are linked
for (int i = 0, start = 0; I < s.length (); i++) {
char C = S.charat (i);
if (Map.containskey (c)) {
A = (Integer) map.get (c); Fixed last position where C appeared
Start = Math.max (Map.get (c) + 1, start); Map.get (c) +1 means starting from the next of the last occurrences of the string; guaranteed start on the right.
Map.get (c) shouldn't be bigger than start? No, when the traversing substring contains the preceding characters, the start is brought to the front;
The function is to distinguish whether the character appearing in the string is the most recent occurrence, and whether to pin the current position to the beginning of the new substring.
}
ret = Math.max (ret, I-start + 1); I-start+1 is to calculate the length of a string between two identical characters, if larger than the original, replace
Map.put (c, i); Finally put the latest C in;
}
return ret;
}
public static void Main (string[] args) {
String s = "Abcdezsdwekjxas";
System.out.println (lengthoflongestsubstring (s));
}
}
Photo reference: http://my.oschina.net/jdflyfly/blog/283405, thank you very much Bo master!
Leetcode-longest Substring without repeating characters