Longest Substring Without Repeating Characters
2017-10-19 19:09
190 查看
//first one,时间复杂度o(n)
//使用map表,键值分别记录每一个字符和其对应的最后一次出现的位置
//start表示最左合法边界,当m[c]>start时出现重复字符,则start+1调整边界
//second one,时间复杂度o(n)
//也是调整边界
//使用map表,键值分别记录每一个字符和其对应的最后一次出现的位置
//start表示最左合法边界,当m[c]>start时出现重复字符,则start+1调整边界
int lengthOfLongestSubstring(string s) { int res = 0; map<char, int> m; int start = 1; for (int i = 1; i <= s.length(); i++) { char c = s[i - 1]; if (m[c] >= start) { start = m[c] + 1; m[c] = i; } else { m[c] = i; res = max(res, i - start + 1); } } return ret; }
//second one,时间复杂度o(n)
//也是调整边界
int lengthOfLongestSubstring(string s) { // 题意为求不包含重复字符的最长子串 // left用以记录合法的最远左边界位置,last记录字符上一次出现的位置 int ans = 0, left = 0, len = s.length(); int last[255]; memset(last, -1, sizeof last); for (int i = 0; i < len; i++) { // 上次出现位置在当前记录边界之后,即该子串中出现了重复字符,需调整left使得子串合法 if (last[s[i]] >= left) left = last[s[i]] + 1; last[s[i]] = i; ans = max(ans, i - left + 1); } return ans; }
相关文章推荐
- Leetcode #3 Longest Substring Without Repeating Characters
- 133day( Longest Substring Without Repeating Characters)
- Longest Substring Without Repeating Characters最大字串问题
- 【Leetcode】【Medium】Longest Substring Without Repeating Characters
- 3.Longest Substring Without Repeating Characters Leetcode Python
- leetcode-3 Longest Substring Without Repeating Characters经典的动态规划问题
- leetcode_Longest Substring Without Repeating Characters
- 【leedcode】longest-substring-without-repeating-characters
- Longest substring without repeating characters
- [leetcode] Longest Substring Without Repeating Characters
- leetcode longest substring without repeating characters
- LeetCode 3 Longest Substring Without Repeating Characters
- Length of the longest substring without repeating characters
- Longest Substring Without Repeating Characters (最长不重复字符的子序列) Java-O(n)解法
- 字符串 Longest Substring Without Repeating Characters
- My Solution to Longest Substring Without Repeating Characters
- leetcode挨个儿刷150429(5):Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode题解(3)-- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters