在leetcode上面练习题目的时候,经常会有子串(subsequence)和子集(substring)的区别,区分就在于子串总是连续的,而子集可以是字符串内任意字符的组合
题目:Longest Substring Without Repeating Characters
地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
描述:
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) {
int len = s.size();
if(len < 2)return len;
int key = 1;
for(int i = 0; i < len - 1; i ++){
if(s[i] != s[i + 1]){
int count = 2;
for(int j = i + 2; j < len; j ++){
int flag = 0;
for(int k = 1; k <= count; k ++){
if(s[j - k] == s[j])break;
if(k == count)flag = 1;
}
if(flag == 0)break;
count++;
}
key = max(key, count);
}
}
return key;
}
};