题目描述:
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.
1、使用一个数值longest_size来保存最大无重复字串的长度。初始设为0;
2、对于一个字符串分两种情况、重复或者不重复,不重复则该串不再分配字串查找。其本身最大值可以与全局的保存值longest_size做比较更新。
3、对于一个给定重复字符串,找到第一个重复的字符的起始fpos以及第二次出现的序号index,该字串第一个最大无重复长字串长度为index,使用此值比较更新longest_size,后一个待处理最长字串为fpos后到字串结尾,该长度为rlen - fpos - 1(rlen为原始字符串总长度),如果不大于index,则整个查找已经结束,否则,使用该字串执行后续处理。
4、第一次解法使用的递归嵌套做处理,结果提示"Memory Limit Exceeded",空间消耗过多导致长串处理失败。第二次处理采用循环处理,每次保存待处理子串进行下一次字串的处理。
code如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
size_t longest_size = 0;
string leave_string = std::move(s);
while (true)
{
leave_string = substr_norepeate(std::move(leave_string), &longest_size);
if (leave_string.empty())
{
break;
}
}
return longest_size;
}
private:
void update_size(size_t *longest_size, size_t size)
{
if (size > (*longest_size))
{
*longest_size = size;
}
}
string substr_norepeate(const string&& resource, size_t* longest_size)
{
size_t rlen = resource.length();
if (1 == rlen)
{
if (0 == *longest_size)
{
*longest_size = 1;
}
return "";
}
string sub_str;//字串
sub_str.append(1, resource[0]);
for (int index = 1; index < rlen; ++index)
{
char c = resource[index];
size_t fpos = sub_str.find(c);
if (string::npos != fpos)
{
size_t front_longest_string_len = index;
size_t back_longest_string_len = rlen - fpos - 1;
update_size(longest_size, front_longest_string_len);
if (front_longest_string_len >= back_longest_string_len)
{
return "";
}
else
{
return std::move(resource.substr(fpos+1));
}
}
else
{
sub_str.append(1, c);
update_size(longest_size, sub_str.length());
}
}
return "";
}
};