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)。
int lengthOfLongestSubstring(string s) {
string::iterator it = s.begin();
string::iterator oldit = it;
int max = 0;
int now = 0;
for (oldit = s.begin(); oldit != s.end(); oldit++) {
it = oldit;
now = 0;
string tmp = "";
while (tmp.find(*it) == string::npos) {
tmp += *it;
now++; it++;
if (it == s.end()) break;
}
if (now>max) max = now;
}
return max;
}