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.
解题思路:题中所描述的字符包括所有128个ASCII字符,定义一个数组alph记录每个字符出现的位置,并且用一个变量mark记录当前子串起点的位置,变量maxlen记录当前最长的子串的长度,字符的位置随着循环不断往后进行更新,如果出现字符的上一个位置在当前子串起点之后,更新起点的位置为当前字符上一个位置的后一位作为起点,同时判断是否需要更新maxlen。
C/C++
int lengthOfLongestSubstring(char* s) {
int i = -1;
int alph[128] = {0};
for(int i=0;i<128;i++)alph[i]=-1;
int mark = -1;
int maxlen = 0;
while(s[i+1])
{
i++;
int tmp = s[i];
if(alph[tmp]>mark)
{
if(maxlen<i-mark-1)maxlen=i-mark-1;
mark = alph[tmp];
}
alph[tmp] = i;
}
if(maxlen<i-mark)maxlen=i-mark;
return maxlen;
}
Java
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] alph = new int[128];
for(int i=0;i<128;i++)alph[i]=-1;
int i = -1;
int mark = -1;
int maxlen = 0;
while(i+1<s.length()) {
i++;
int tmp = s.charAt(i);
if(alph[tmp]>mark) {
if(maxlen<i-mark-1)maxlen=i-mark-1;
mark = alph[tmp];
}
alph[tmp] = i;
}
if(maxlen<i-mark)maxlen=i-mark;
return maxlen;
}
}
Python
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
alph = []
for i in range(128):alph.append(-1)
i = -1
mark = -1
maxlen = 0
while i+1<len(s):
i += 1
tmp = ord(s[i])#字符转整型要用函数,不可直接赋值
if alph[tmp]>mark:
if maxlen<i-mark-1:maxlen=i-mark-1
mark = alph[tmp]
alph[tmp] = i;
if maxlen<i-mark:maxlen=i-mark
return maxlen