Decription
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.
解题思路
由于是找不重复子串的最大值,在STL中恰好有一个模板类型Set,集合Set中的值都是唯一的,因此本题借助了Set。我们可以利用双重循环
Code
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.size();
int max = 0;
if(len == 0){
return max;
}
max = 1;
set<char> cset;
int num = 0;
for(int i=0;i<len;i++){
for(int j = i;j<len;j++){
cset.insert(s[j]); //插入字符到set集合中
if(cset.size()>num){ //新插入的字符是“新”字符
num = cset.size(); //重新给num赋值,确保num值为当前最大值
continue;
}
break; //出现重复字符时跳出内层循环
}
if(num >max){
max = num;
}
num = 0;
cset.clear();
}
if(num >max){
max = num;
}
return max;
}
};