码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 3.Longest Substring Without Repeating Characters

时间:2015-01-05 00:18:13      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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 before
12             {
13                 suffix_max++;
14             }
15             else
16             {
17                 if (last_visit <= table[s[i]])
18                 {
19                     suffix_max = i - table[s[i]];
20                     last_visit = table[s[i]] + 1;
21                 }
22                 else
23                 {
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

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4202429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!