Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “baab”, the answer is “ba”, with the length of 2.
实现(Java):
import java.util.HashMap;
public class test {
public static void main(String[] args) {
String str = "baab";
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
for (int i = 0, j = 0; i < str.length(); i++) {
if (map.containsKey(str.charAt(i))) {
j = Math.max(j, (map.get(str.charAt(i)) + 1));
}
map.put(str.charAt(i), i);
max = Math.max(max, i - j + 1);
}
System.out.print(max);
}
}