LeetCode OJ Longest Substring Without Repeating Characters
2015-03-22 17:33
447 查看
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
这个方法没有任何算法可言,448ms(当然其实leetcode上的时间统计好像不准- -)
以下这个比较好:100ms
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1
class Solution { public: int lengthOfLongestSubstring(string s) { int ans = 0; for (int i = 0; i < s.size(); i++) { bool exist[256]; int j; for (j = 0; j < 256; exist[j++] = false); for (j = i; j < s.size() && j < i + 256; j++) { if (exist[s[j]] == true) break; else exist[s[j]] = true; } ans = ans < j - i ? j - i : ans; } return ans; } };
这个方法没有任何算法可言,448ms(当然其实leetcode上的时间统计好像不准- -)
以下这个比较好:100ms
class Solution { public: int lengthOfLongestSubstring(string s) { int maxDis = 0, newDis = 0; int latestPos[256]; // to record a character's latest position for (int i = 0; i < 256; latestPos[i++] = -1); // -1 means no record for (int i = 0; i < s.size(); i++) { if (latestPos[s[i]] == -1 || latestPos[s[i]] < i - newDis) // if no record or the latest position is too far for the new distance newDis++; else newDis = i - latestPos[s[i]]; // else the new distance is the distance between 2 same characters latestPos[s[i]] = i; // renew the record if (newDis > maxDis) maxDis = newDis; } return maxDis; } };
相关文章推荐
- leetcode_oj_Longest Substring Without Repeating Characters
- LeetCode OJ Longest Substring Without Repeating Characters 不重复的最长字串 滑动窗口
- 【LeetCode】LeetCode——第3题: Longest Substring Without Repeating Characters
- [C++]LeetCode 3: Longest Substring Without Repeating Characters(最长不重复子串)
- LeetCode Algorithm Longest Substring Without Repeating Characters
- leetCode之Longest Substring Without Repeating Characters实现
- leetcode_Longest Substring Without Repeating Characters
- LeetCode-string-Longest Substring Without Repeating Characters
- Leetcode Longest Substring Without Repeating Characters
- LeetCode 第 3 题(Longest Substring Without Repeating Characters)
- leetcode Longest Substring Without Repeating Characters
- 【LeetCode】003 Longest Substring Without Repeating Characters 最长的没有重复的子字符串
- 算法分析与设计——LeetCode Problem.3 Longest Substring Without Repeating Characters
- Leetcode-Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- [Leetcode]Longest Substring Without Repeating Characters
- leetcode第七题----- Longest Substring Without Repeating Characters
- LeetCode之Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters Python