LeetCode OJ

题目:

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.

解题思路:

用哈希表site来记录每个字符最近出现的起始位置。用nowstart记录不重复区间的第一个字符。

代码:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         vector<int> site(128, -1);
 5         int nowstart = -1, ans = 0;
 6         for(int i = 0; i < s.length(); i ++)
 7         {
 8             if(site[s[i]] >= nowstart)
 9                 nowstart = site[s[i]] + 1;
10             site[s[i]] = i;
11             ans = max(i - nowstart + 1, ans);
12         }
13         return ans;
14     }
15 };
原文地址:https://www.cnblogs.com/dongguangqing/p/3810693.html