首页 > 代码库 > leetcode 3.Longest Substring Without Repeating Characters

leetcode 3.Longest Substring Without Repeating Characters

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.

采用动态规划求解:对于已知字符串S[1, ..., k], 使用哈希表table[256]记录S[i]出现的位置,初始为-1.

假设已知包含后缀S[k]的子串的最长不重复长度为suffix_max[k], 那么对于S[1, ..., k+1],

a) 如果table[S[k+1]] 为-1, 说明S[k+1]第一次出现,suffix_max[k+1] = suffix_max[k] + 1;

b)否则,用last_visit记录S[k+1]上一次出现的位置,如果last_visit <= table[S[i]], 

 1 int lengthOfLongestSubstring(string s) 2     { 3         int table[256]; 4         int suffix_max = 0; // suffix_max 包含后缀的最大长度 5         int global_max = 0; 6         int last_visit = 0; // 上一次 7          8         memset(table, -1, 256 * sizeof(int)); 9         for (int i = 0; i < s.size(); i++)10         {11             if (table[s[i]] == -1) // not appear before12             {13                 suffix_max++;14             }15             else16             {17                 if (last_visit <= table[s[i]])18                 {19                     suffix_max = i - table[s[i]];20                     last_visit = table[s[i]] + 1;21                 }22                 else23                 {24                     suffix_max++;25                 }26             }27             hash[s[i]] = i;28             if (global_max < suffix_max)29                 global_max = suffix_max;30         }31         32         return global_max;33     }

 

leetcode 3.Longest Substring Without Repeating Characters