转载请注明出处:
http://write.blog.csdn.net/postedit/78093572
题目:
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 "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
JAVA版1:
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int i = 0, j = 0; i < s.length(); ++i){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - j + 1);
}
return max;
}
JAVA版2:
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int i = 0, j = 0; i < s.length(); ++i){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-j+1);
}
return max;
}
说明:
答案并不难理解,核心是 HashMap。关键是下面这句
j = Math.max(j,map.get(s.charAt(i))+1)
情况1:a d c d e f g e c m u
情况2:a d n d e f c e c m u
情况1 中,当 j 指向 f ,i 指向 c 的时候,c 元素重复,但是重复的位置却在 j 之前,
这种情况下, j 不需要更新,只有对于 情况2 时才需要更新 j 值
答案2 的变化是使用单一的数组取代 HashMap,原来上和 答案1 是一样的