[LeetCode-Algorithms-3] "Longest Substring Without Repeating Characters" (2017.9.8)
2017-09-08 21:47
375 查看
题目链接:Longest Substring Without Repeating Characters
题目描述:Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
<1>题目思路:贪心,用两变量标记头尾,lon为所求的不重复字符串长度,从字符串头部开始,字符不重复时尾部变量往后增加,有字符和之前的字符串中某字母重复时,头部变量相应后推,由于使用内外双层循环,时间复杂度为O(n2)。
<2>代码:
int lengthOfLongestSubstring(char* s) { int len = strlen(s); int lon = 0, i; int bgt = 0, end; for(end = 0; end < len; end++){ for(i = bgt; i < end; i++) { if(s[end] == s[i]) bgt = i + 1; } if(lon <= end - bgt) lon = end - bgt + 1; } return lon; }
<3>提交结果:
<4>向他人学习:我在讨论中看到了C++的一种解法,52.2%的defeat率,觉得想法也是比较好,留在这里作为学习。
class Solution { public: int lengthOfLongestSubstring(string s) { int last[128]; int start = -1, ans = 0; for(int i = 0; i < 128; i++) last[i] = -1; for(int i = 0; i < s.length(); i++) { if (last[s[i]] > start) start = last[s[i]]; last[s[i]] = i; ans = ans > i-start ? ans : i-start; } return ans; } };
相关文章推荐
- [LeetCode]-algorithms-Longest Substring Without Repeating Characters
- LeetCode "Longest Substring Without Repeating Characters"
- LeetCode之Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters leetcode
- (leetcode) Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- Java [leetcode 3] Longest Substring Without Repeating Characters
- LeetCode 第 3 题(Longest Substring Without Repeating Characters)
- LeetCode-- Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode]-003-Longest Substring Without Repeating Characters
- LeetCode3:Longest Substring Without Repeating Characters
- leetcode008-Longest Substring Without Repeating Characters
- leetcode:3 Longest_Substring_Without_Repeating_Characters
- leetcode--136--Longest Substring Without Repeating Characters
- LeetCode -- Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- LeetCode3:Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode题解 #3 Longest Substring Without Repeating Characters