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.
時間複雜度O(n^2)
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
size_t found;
int max_len = s.empty() ? 0 : 1;
size_t prev = 0, next = 1;
int len = 1;
while (next < s.size()) {
found = find(s.at(next), s, prev, next);
if (found == string::npos) {
++len;
++next;
} else {
if (len > max_len) {
max_len = len;
}
prev = found + 1;
len = next - prev + 1;
++next;
}
}
// 防止最後一個窗口沒有將較大的len賦值給max_len,同時考慮s爲空的情形
if (len > max_len && !s.empty()) {
max_len = len;
}
return max_len;
}
private:
size_t find(char ch, string s, size_t start_pos, size_t end_pos) {
size_t pos = start_pos;
while (pos < end_pos) {
if (s.at(pos) == ch) {
return pos;
}
pos++;
}
return string::npos;
}
};
int main() {
string str1 = "abcabcbb";
string str2 = "bbbbb";
string str3 = "pwwkew";
string str4 = "au";
string str5 = "a";
string str6;
Solution s;
cout << s.lengthOfLongestSubstring(str1) << endl
<< s.lengthOfLongestSubstring(str2) << endl
<< s.lengthOfLongestSubstring(str3) << endl
<< s.lengthOfLongestSubstring(str4) << endl
<< s.lengthOfLongestSubstring(str5) << endl
<< s.lengthOfLongestSubstring(str6) << endl;
return 0;
}