Longest Substring Without Repeating Characters
Q:
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.
A:
遍历字符串,计算以当前字符结尾的最长连续子串长度,该长度与最近的该字符所在的位置有关,所以遍历每个字符的同时存储该字符所在的位置,字符总数256,占用空间同样是256,ok
class Solution { public: int lengthOfLongestSubstring(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.empty()) return 0; vector<int> nearest_pos; nearest_pos.assign(256, -1); nearest_pos[s[0]] = 0; int part_longest = 1; // 代表以当前字符结尾的最长不重复子串 int result = 1; for (int i = 1; i < s.length(); ++i) { if (nearest_pos[s[i]] < i - part_longest) { part_longest += 1; result = max(result, part_longest); } else { part_longest = i - nearest_pos[s[i]]; } nearest_pos[s[i]] = i; } return result; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号