首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。