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.
翻译
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定 “abcabcbb” ,没有重复字符的最长子串是 “abc” ,那么长度就是3。
给定 “bbbbb” ,最长的子串就是 “b” ,长度是1。
给定 “pwwkew” ,最长子串是 “wke” ,长度是3。请注意答案必须是一个子串,“pwke” 是 子序列 而不是子串。
分析
构建一个set,将字符依次放入set,重复就跳出,遍历完返回最大的set元素个数。
c++实现
class Solution {
public:
int lengthOfLongestSubstring(string s) {
set<char> s1;
int length = 0;
for (int i = 0; i < s.length(); i++)
{
int j;
for (j = 1; i-1+j < s.length(); j++)
{
if (s1.find(s[i-1+j]) == s1.end())
s1.insert(s[i-1+j]);
else
break;
}
if (j-1 > length)
length = j-1;
s1.clear();
}
return length;
}
};