题目:
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.
分析:
这道题的意思是任意给一个字符串,找出其中最长的没有重复字符的子串。
解法一:
用一个变量start来记录子串的开始位置,用两个整型数组temp和pos来记录每个字符在子串中是否出现和出现的位置,遍历整个字符串,若当前字符没有出现过,更新temp和pos数组对应位置的值,表示该字符在当前子串中已经出现过和出现的位置;若当前字母已经出现过了,则更新数组temp和pos的值,并将start移动到该字母上次出现的位置的后一位。
需要注意一点:在更新start前,要将start和字符上次出现的位置中间的那些字符的temp更新,表示那些字符在新的子串中还没有出现过。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxnum = 0;
int start = 0;
int pos[256] = {-1};
int temp[256] = {0};
for(int i = 0;i<s.length();i++)
{
if(temp[s[i]-' '])
{
for(int j = start;j<pos[s[i]-' '];j++)
temp[s[j]-' '] = 0;
start = pos[s[i]-' ']+1;
pos[s[i]-' '] = i;
}
else
{
temp[s[i]- ' '] = 1;
pos[s[i]-' '] = i;
}
if(i-start+1>maxnum)
maxnum = i-start+1;
}
return maxnum;
}
};
解法二:
还有一种解法是只用一个整型数组temp来表示每个字符出现的位置,遍历一遍字符串,当有字符的上次出现的位置大于start,表示该字符在子串中已经出现过一次了,这时更新start的值。每次循环都判断一下最大子串长度。这个解法的复杂度为O(n)。
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxnum = 0;
int start = -1;
int l = s.length();
int temp[256];
memset(temp, -1, sizeof(temp));
for(int i = 0;i<l;i++)
{
if(temp[s[i]-' ']>start)
{
start = temp[s[i]-' '];
}
if(i-start>maxnum)
{
maxnum = i-start;
}
temp[s[i]-' '] = i;
}
return maxnum;
}
};