您的位置:首页 > 其它

LeetCode 3: Longest Substring Without Repeating Characters

2013-08-27 20:00 459 查看
Difficulty: 3

Frequency: 2

Problem:

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.

Solution:

class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i_max_length = 0, i_max_length_from_end = 0;
int p_last_index[26];
memset(p_last_index, 0xFF, sizeof(int)*26);
for (int i = 0; i<s.size(); i++)
{
if (p_last_index[s[i]-'a']==-1||(i-p_last_index[s[i]-'a'])>i_max_length_from_end)
{
p_last_index[s[i]-'a'] = i;
i_max_length_from_end++;
i_max_length = i_max_length>i_max_length_from_end?i_max_length:i_max_length_from_end;
}
else
{
i_max_length_from_end = i - p_last_index[s[i]-'a'];
p_last_index[s[i]-'a'] = i;
}
}
return i_max_length;
}
};
Notes:
Time complexity O(n).

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: