一,题目
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.
使用两个指针一个指向子串的头,一个指向子串的尾, 然后一直向后移动尾指针,将每次一动的元素保存到hashmap key是字符值,value是其在字符串中对应的索引。
每次移动尾指针,判断其是否在hashmap中,如果不在,继续后移动;否则,说明找到了一个不重复的子串,比较长度,然后头指针向前移动一个,然后继续一直移动尾指针。
三,代码如下
public int lengthOfLongestSubstring(String s) {
<span style="white-space:pre"> </span>int maxLen = 0;
if (s == null) {
<span style="white-space:pre"> </span>return maxLen;
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
int start = 0;
for (int i = 0, len = s.length(); i < len; i++) {
char c = s.charAt(i);
Integer index = map.get(c);
if (index != null) {
if(index < start){
map.put(c,i);
continue;
}
maxLen = maxLen > i - start ? maxLen : i - start;
start = index+1;
}
map.put(c, i);
}
maxLen = maxLen > (s.length() - start) ? maxLen : s.length() - start;
return maxLen;
}