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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
string max_str = "";
string temp = "";
char ch;
for(int i=0; i<s.length(); i++)
{
ch = s[i];
int idx = temp.find(ch);
if(idx==string::npos)
{
temp += s[i];
}
else
{
temp = temp.substr(idx+1);
temp += s[i];
}
if(temp.length()>=max_str.length())
{
max_str = temp;
}
}
return max_str.length();
}
};
本文介绍了一种寻找字符串中最长无重复字符子串的算法实现。通过遍历字符串并利用临时变量记录当前无重复子串,该算法能够有效地找到最长的不包含重复字符的子串,并返回其长度。
949

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



