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.
看错题了,题目要求找出字符串中的一个最长的子串,使得这个子串不包含重复的字符,这个子串的长度。看成了找出一个最长重复子串,它不包含重复的字符。题目给的两个例子也恰好符合我的臆想,想想也是醉了。
写了一些臆想的代码:
unordered_set<char> tmp;
bool is_unique(string& s)
{
tmp.clear();
for(int i=0; i!= s.size(); ++i)
{
if(tmp.find(s[i]) != tmp.end())
return false;
tmp.insert(s[i]);
}
return true;
}
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<string> allsubstrings;
int maxlength = 1;
int i, j;
string str;
for(i=0; i!= s.size(); ++i)
{
for(j =i+maxlength; j<= s.size(); ++j)
{
str = s.substr(i,j-i);
if(is_unique(str))
{
if(allsubstrings.find(str) != allsubstrings.end())
{
if(maxlength < str.size())
maxlength = str.size();
}
else
{
allsubstrings.insert(str);
}
}
else
{
break;
}
}
}
return maxlength;
}
}; 原题的解:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int i = 0, j = 0;
int maxLen = 0;
bool exist[256] = { false };
while (j < n) {
if (exist[s[j]]) {
maxLen = max(maxLen, j-i);
while (s[i] != s[j]) {
exist[s[i]] = false;
i++;
}
i++;
j++;
} else {
exist[s[j]] = true;
j++;
}
}
maxLen = max(maxLen, n-i);
return maxLen;
}
本文提供了解决字符串问题的代码实现,目标是在给定字符串中找到最长的子串,该子串不含重复字符。通过使用unordered_set来辅助查找,确保子串的唯一性。

555

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



