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.
解析:找出给定字符串中无重复子串的最大长度。解法是采用一种“滑动窗口”的策略,比如给定一字符串"abcda",那么我可以先扫描一遍,扫描过的字符可以通过建立哈希表来记录其下标,每次扫描都查询一下当前字符是否出现在已扫描过的字符当中,即查找key(字符)所对应的value(下标)是否存在,若存在,则更新“窗口左边界”(方便计算子串长度)和字符对应下标再继续扫描,每次扫描都更新一遍最大长度。例如在找到了无重复子串"abcd"后,当我继续扫描时,发现字符"a"重复了,那么我可以将原来的"a"丢弃,添加新的"a"以更新扫描子串(即更新“窗口左边界”和字符对应下标),这样再以"bcda"的形式继续扫描,以此类推…。
解法:①C++
int lengthOfLongestSubstring(string s) {
int len=s.length(),maxlen=0,bound=0; //bound为“窗口左边界”
map<char,int> mp;
for(int i=0;i<len;i++){
if(mp.find(s[i])!=mp.end()) bound=max(bound,mp[s[i]]+1); //更新窗口边界
maxlen=max(maxlen,i-bound+1); //更新子串最大长度
mp[s[i]]=i;
}
return maxlen;
}
//另一种写法:
int lengthOfLongestSubstring(string s) {
int len=s.length(),maxlen=0,curPos=-1;
map<char,int> pos; //记录字符对应下标
for(int i=0;i<len;i++) pos[s[i]]=-1;
for(int i=0;i<len;i++){
//若无出现重复字符,则子串长度i-curPos的结果就是不断+1,当字符重复时,
//curPos为字符最新出现的地方
curPos=max(curPos,pos[s[i]]);
maxlen=max(maxlen,i-curPos); //更新长度
pos[s[i]]=i; //更新下标
}
return maxlen;
}
②Java
import java.util.HashMap;
class Solution {
public int lengthOfLongestSubstring(String s) {
int len=s.length(),maxlen=0,bound=0;
HashMap<Character,Integer> pos=new HashMap<>();
for(int i=0;i<len;i++){
char ch=s.charAt(i);
if(pos.containsKey(ch)) bound=Math.max(bound,pos.get(ch)+1); //更新“窗口左边界”
maxlen=Math.max(maxlen,i-bound+1); //更新长度
pos.put(ch,i);
}
return maxlen;
}
}