leetcode/3.longest substring without repeating characters example answer:


Given a string, find the length of the longest substring without repeating characters.

example

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.

answer:

遍历s,用HashMap记录,在HashMap中没有出现过的字符,放入,并随时记录最长非重复子串的长度。当遇到出现过的字符,清空map,并从这个字符出现的index的下一位开始重新记录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null){
return 0;
}
else if (s.length() <= 1){
return s.length();
}
int longest = -1;
HashMap <Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
longest = Math.max(map.size(),longest);
i = map.get(c);
map.clear();
}
else{
map.put(c,i);
longest = Math.max(map.size(),longest);
}
}
map.clear();
return longest;
}
}