[Leetcode 41] 3 Longest Substring Without Repeating Characters

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:

There's a one pass algorithm. With the help of a hash table. We can scan through the given string and hash every character into the hash table.

If ht[a] == 0, then there is no collision, we increase the current substring length and continue.

If ht[a] != 0, there is a collision. In such case, we do two things: 1) update the max substring length; 2) adjust the length and substring start index to the right position.

For 1, we only need to compare the current length with the max length and update max length;

For 2, we start from the current index, and go through until the current position. Each time we process a character, decrease the current length and increase index. Until we find the collision character or reach the newest character cause the problem. Thus we can have the next substring doesn't have collision. Then repeat.

Code:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (s.size() == 0) return 0;
 7         
 8         char ht[26];
 9         int maxLen = 0, len = 0, idx = 0;
10         
11         for (int i=0; i<26; i++)
12             ht[i] = 0;
13         
14         for (int i=0; i<s.size(); i++) {
15             if (ht[s[i] - 'a'] == 0) {
16                 ht[s[i] - 'a']++;
17                 len++;
18             } else {
19                 if (len > maxLen)
20                     maxLen = len;
21                 
22                 for (; idx<i; idx++) {    
23                     if (s[idx] == s[i]) {
24                         idx++;
25                         break;
26                     } else {
27                         len--;
28                         ht[s[idx] - 'a']--;
29                     }
30                 }
31             }
32         }
33         
34         if (len > maxLen) maxLen = len;
35         return maxLen;
36     }
37 };
View Code

Attention:

原文地址:https://www.cnblogs.com/freeneng/p/3096508.html