您的位置:首页 > 其它

LeetCode (33) Longest Substring Without Repeating Characters

2015-05-07 14:49 423 查看

题目描述

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.

解题思路

如下图所示:左侧为遍历字符串操作,当遇到重复的字符串时,得到的新的substring为重复字符串后面部分的字符串与被遍历到的字符串相连部分。例如当”abc”遍历到第四号位的’a’时,原substring中的”bc”被保留,并与新的字符串相连。



代码

class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 1 || !s.size())
return s.size();
string sub;

int max = 0;
for (size_t i = 0; i != s.size(); ++i)
{
char c = s[i];
if (sub.find(c) != string::npos)
{
max = max > sub.size() ? max : sub.size();
int idx = sub.find(c);
sub = sub.substr(idx + 1);
}
sub.append(1, c);
}
max = max > sub.size() ? max : sub.size();
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: