题目地址 点击打开链接
题目描述:
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 index = 0;
- int max = 0;
- int len = s.length();
- if( len == 0)
- return 0;
- if (len ==1)
- return 1;
- for (int i =1; i< len; i++)
- {
- for(int j=i-1; j>=index; j--)
- {
- if(s[i] == s[j])
- {
- index = j+1;
- break;
- }
- else
- {
- if(max < i-j+1)
- max = i - j +1;
- }
- }
- }
- return max;
- }
- };
附送大神代码 :
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};