Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> hmap;
int start=0,end=0,i;
int max = 0,count=0;
int loc[256];
for(i=0;i<256;i++)
loc[i] = -1;
for(start=0;start<s.length();start++)
{
if(!hmap.count(s[start]))
{
loc[s[start]]=start;
count++;
hmap.insert(pair<char,int>(s[start],1));
}
else
{
if(count > max)
max = count;
hmap.clear();
count = 0;
start = loc[s[start]];
}
}
if(count > max)
max = count;
return max;
}
};
这个方法出现了超时的情况。根据分析,每次遇到重复字符进行hmap.clear()费时,并且会浪费时间重新映射下一次计算子串长度的有用信息。进行改进,当遇到相同字符,只需要把子串位置调整到前一个相同字符的位置+1开始,然后把上一次子串的起始位置到现在子串的起始位置之间的字符在hash表中设置为空。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
bool canUse[256];
int loc[256];
int start=0;
int count=0;
int i=0;
int ret = 0;
for(i=0;i<256;i++)
{
canUse[i] = false;
loc[i] = -1;
}
for(i=0;i<s.size();i++)
{
if(canUse[s[i]] == false)
{
canUse[s[i]] = true;
loc[s[i]] = i;
count++;
}
else
{
ret=max(count,ret);
for(;start<=loc[s[i]];start++)
{
canUse[s[start]] =false;
count--;
}
count++;
canUse[s[i]] = true;
loc[s[i]] = i;
}
}
ret=max(count,ret);
return ret;
}
};
历遍字符串,当当前字符出现过的时候,计算子串长度,子串开始位置更改,否则更新locs数组中的hash值为当前位置
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int locs[256];
memset(locs, -1, sizeof(locs));
int i;
int idx = -1, max = 0;
for ( i = 0; i < s.size(); i++)
{
if (locs[s[i]] > idx)
{
if (i - idx-1 > max)
{
max = i - idx-1;
}
idx = locs[s[i]];
}
locs[s[i]] = i;
}
if(i==0)
return max;
else
{
if (i - idx-1 > max)
{
max = i - idx-1;
}
return max;
}
}
};