您的位置:首页 > 其它

Longest Substring Without Repeating Characters

2013-05-14 16:20 155 查看
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.

class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<char, const char*> chars_map;
const char* p = s.c_str();
int max_length = 0;
int cur_length = 0;
const char* pre_char = NULL;
const char* p_begin = p;
while (*p) {
map<char, const char*>::iterator it = chars_map.find(*p);
if (it != chars_map.end()) {
if (max_length < cur_length) {
max_length = cur_length;
}
pre_char = it->second;
cur_length = p - pre_char;
while (p_begin != pre_char) {
if (*p_begin != *pre_char) {
chars_map.erase(*p_begin);
}
++p_begin;
}
it->second = p;
p_begin = ++pre_char;
++p;
} else {
chars_map.insert(make_pair(*p, p));
++cur_length;
++p;
}
}
max_length = max_length < cur_length ? cur_length : max_length;
return max_length;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: