您的位置:首页 > 编程语言 > C语言/C++

[3, Medium, C++] Longest Substring Without Repeating Characters

2016-01-10 05:55 429 查看
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.

Analysis:

To solve this question, the program first caches a set of distinct characters of the string and runs from the first one to the
last one to check whether a repeated character of the set is met. If such character is met, remove all ones before the repeated character. The key point of this method is to locate the repeated one in the quickest way.The method here is a typical one.
We use a characteristic array whose index is the ascii value of a character and value is the index this character. For each character of the string, if the corresponding characteristic value of this character is greater or equal of the current sub-string,
it means that a repeated character is found. Then, update the local_max_length of the sub-string and new start-checking-point. 

Sample Code:

int lengthOfLongestSubstring(string s) {
if(s.size() <= 1)
return s.size();

int max_length = 0;
vector<int> char_seq_index(256, -1);
int start_point = 0;
int local_max_length = 0;
for(int i = 0; i < s.size(); ++i) {
if(char_seq_index[s[i]] >= start_point) {
local_max_length -= char_seq_index[s[i]] + 1 - start_point;
start_point = char_seq_index[s[i]] + 1;
}

char_seq_index[s[i]] = i;
++local_max_length;

if(local_max_length > max_length)
max_length = local_max_length;
}

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