题目描述:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
思路1:滑动窗口的思想,slow,fast指针来模拟窗口
用HashSet来保存当前最长的不含重复字符的字符串,我们用快指针来判断当前字符是否存在于HashSet中,若不存在,则加入set, 若已经存在,则用slow指针从前开始一出,直到移除重复的字符后,再次加入新的字符。在遍历的过程中,不断的判断更新最长不重复字串的长度
实现1:
public int lengthOfLongestSubstring(String s) {
int slow=0,fast=0,ret=0;
HashSet<Character> set=new HashSet<>();
while(fast<s.length()){
if(!set.contains(s.charAt(fast))){
set.add(s.charAt(fast++));
ret=Math.max(ret,set.size());
}else {
set.remove(s.charAt(slow++));
}
}
return ret;
}
实现2:
和上面思路一样
public int lengthOfLongestSubstring2(String s) {
HashSet<Character> set=new HashSet<>();
int ret=0;
int tail=0;
for(int head=0;head<s.length();head++){
while (tail<=head&&set.contains(s.charAt(head))){
set.remove(s.charAt(tail++));
}
set.add(s.charAt(head));
ret=Math.max(ret,set.size());
}
return ret;
}
思路2:
用哈希表存储,若存在重复的,则记下重复元素的索引,并在遍历过程中不断更新最大长度。
public int lengthOfLongestSubstring3(String s) {
int maxlen=0;
int tail=-1;//用来记录与当前字符重复的字符所在的索引位置
HashMap<Character,Integer> map=new HashMap<>();
for (int i = 0; i < s.length(); i++) {
Character ch=s.charAt(i);
Integer old=map.get(ch);
map.put(ch,i);
if(old!=null&&old>tail){
tail=old;
}
maxlen=Math.max(maxlen,i-tail);
}
return maxlen;
}