题目
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. 使用一个临时字符串存放子串T
2. 每次从输入中获取一个字符C,并检查已有的子串T中是否已经存在该字符
- 如果存在,删除该字符之前的所有字符和它自己
3. 将C追加在子串T的尾部
4. 获取子串T的长度,并决定是否要更新最大值MAX
5. 重复1~4步骤,直到输入的所有的字符都处理完
6. 返回最大值MAX
本人的解
根据上述思路,代码如下。耗时29毫秒。
class Solution {
public:
/* 29 ms, Your runtime beats 51.30% of cpp submissions */
int lengthOfLongestSubstring(string s) {
int max = 0;
string t("");
for( int i = 0; i < s.length(); i++ ) {
size_t pos = t.find(s[i], 0);
if( pos != string::npos ) t.erase(0, pos + 1);
t.append(1, s[i]);
if( t.length() > max ) max = t.length();
}
return max;
}
};改进版。
class Solution {
public:
/* 12 ms, Your runtime beats 87.44% of cpp submissions */
int lengthOfLongestSubstring(string s) {
int max = 0;
string t("");
while( s.length() ) {
char a = s.back();
size_t pos = t.find(a, 0);
if( pos != string::npos ) t.erase(0, pos + 1);
t.append(1, a);
if( t.length() > max ) max = t.length();
s.pop_back();
}
return max;
}
};
本文介绍了一种解决最长无重复字符子串问题的有效算法,通过迭代检查字符并更新子串,实现快速查找。提供了两种不同优化级别的C++实现方案。

被折叠的 条评论
为什么被折叠?



