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 subsequenceand not a substring.
Solution:
1.暴力解法:(超时)
利用枚举思想,列举所有情况。显然时间复杂度达到O(n³)。
2.贪心算法
最长无重复子串肯定包含在两个重复字符之间,用len保存当前最长的子串。如果某两个重复字符之间的子串长于maxLen,则给maxLen赋值这个新的长度。用i,j分别表示头和尾,k用于查找重复。这样只需要2重循环就可以了。
//22ms
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0;
int i = 0, j = 0;
int n = s.length();
for (; j < n; j++) {
bool f = true;
for (int k = i; k < j; k++) {
if (s[k] == s[j]) {
i = k+1;
f = false;
}
}
if (f) {
maxLen = max(maxLen,j - i + 1);
}
}
return maxLen;
}
};