Longest Substring Without Repeating Characters

 1 class Solution {
 2 public:
 3   
 4     int lengthOfLongestSubstring(string s) {
 5     // for ASCII char sequence, use this as a hashmap
 6     vector<int> charIndex(256, -1);
 7     int longest = 0, m = 0;
 8 
 9     for (int i = 0; i < s.length(); i++) {
10         m = max(charIndex[s[i]] + 1, m);    // automatically takes care of -1 case//保证每次都找到不同的序列的第一个序号
11         charIndex[s[i]] = i;
12         longest = max(longest, i + 1- m);
13     }
14 
15     return longest;
16 }
17     
18 };
charIndex[s[i]]就是上个相同同的索引号的最大一个

假设不同的序列长度为[m,i],则当新出现一个不在序列里时,longest加1通过使序列号自增 ;当遇到相同时,则m要进行更新到下一个不含相同字符的第一个,并且新的不重复段也变成i+1-m。
原文地址:https://www.cnblogs.com/daocaorenblog/p/4782934.html