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.
本題比較簡單,需要注意的是左指針右移時,需要將它掠過的元素從map中移除。實現代碼如下:
1 public class Solution {
2 public int lengthOfLongestSubstring(String s) {
3 int length = s.length();
4 if (length == 0) return 0;
5 Map<Character, Integer> map = new HashMap<Character, Integer>();
6 int ret = 0;
7 int count = 0;
8 int start = 0;
9 for (int i = 0; i < length; i++) {
10 char c = s.charAt(i);
11 if (map.containsKey(c)) {
12 int newStart = map.remove(c).intValue() + 1;
13 for (int j = start; j < newStart; j++) {
14 map.remove(s.charAt(j));
15 }
16 start = newStart;
17 ret = ret < count ? count : ret;
18 count = i - start + 1;
19 } else {
20 count++;
21 }
22 map.put(c, i);
23 }
24 return ret < count ? count : ret;
25 }
26 }
2 public int lengthOfLongestSubstring(String s) {
3 int length = s.length();
4 if (length == 0) return 0;
5 Map<Character, Integer> map = new HashMap<Character, Integer>();
6 int ret = 0;
7 int count = 0;
8 int start = 0;
9 for (int i = 0; i < length; i++) {
10 char c = s.charAt(i);
11 if (map.containsKey(c)) {
12 int newStart = map.remove(c).intValue() + 1;
13 for (int j = start; j < newStart; j++) {
14 map.remove(s.charAt(j));
15 }
16 start = newStart;
17 ret = ret < count ? count : ret;
18 count = i - start + 1;
19 } else {
20 count++;
21 }
22 map.put(c, i);
23 }
24 return ret < count ? count : ret;
25 }
26 }