题目:
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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
bool a[256] = { false };
for (int i = 0; i < 256; i++) a[i] = false;
int temMax = 0,i=0,j;
for ( j = 0; j < s.length(); j++) {
if (!a[s[j]]) {
a[s[j]] = true;
}
else {
temMax=temMax > j - i ? temMax : j - i;
while (s[i] != s[j]) {
a[s[i]] = false;
i++;
}
i++;
}
}
temMax = temMax > s.length() - i ? temMax : s.length() - i;
return temMax;
}
};