您的位置:首页 > 其它

Longest Substrings Without Repeating Characters

2015-09-03 01:34 435 查看
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Analyse: set two pointers, index1 and index2. When index2 is less than the length of the string, check interval s[index1...index2] and find whether there is duplicate number with s[index2]. If yes, index1++, else index2++. Remember to update the result.

Runtime: 20ms.

class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length() <= 1) return s.length();

int index1 = 0, index2 = 1;
int result = INT_MIN;
for(; index2 < s.length(); index2++){
for(int i = index1; i < index2; i++){
if(s[i] == s[index2]){
index1 = i + 1;
break;
}
}
result = max(result, index2 - index1 + 1);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: