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.
本题的解题思路就是设置两个指针m,n和一个hash表记录字符的索引,两个同时从字符串的第一个字符出发,如果hash表中没有n所在位置的字符信息,n不断向后移动。否则如果hash表中有n的字符的信息,处理m:
m用来记录每次计算当前局部最大子串长度时子串的开头字符的位置。如果m的值小于等于n所在字符出现的上一个索引,则m=上一个索引+1。
Java代码
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s==null){
return 0;
}
if(s.length()==0||s.length()==1){
return s.length();
}
int max=0,curMax=0;
int[] keyMap = new int[256];//测试的字符串都是英文字符,此处可以用一个256长度的数组来模拟hashmap
for(int i=0;i<keyMap.length;i++){
keyMap[i]=-1;
}
int m=0,n=0;
while(n<s.length()){
if(keyMap[s.charAt(n)]==-1){
curMax=n-m+1;
}else{
if(keyMap[s.charAt(n)]>=m){//此处必须为>=,abba
m=keyMap[s.charAt(n)]+1;
}
curMax=n-m+1;
}
keyMap[s.charAt(n)]=n;
n++;
if(curMax>max){
max=curMax;
}
}
return max;
}
}
Go代码
func lengthOfLongestSubstring(s string) int {
if len(s)==0||len(s)==1{
return len(s)
}
var i,j int
var max int
var keyMap map[byte]int=make(map[byte]int)
var curMax int
for j=0;j<len(s);{
if _,ok:=keyMap[s[j]];!ok{
curMax=j-i+1
keyMap[s[j]]=j
j++
}else{
if i<=keyMap[s[j]]{
i=keyMap[s[j]]+1
}
keyMap[s[j]]=j
curMax=j-i+1
j++
}
if curMax>max{
max=curMax
}
}
return max
}