[LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C++/Java/Python)
2015-02-27 12:55
555 查看
索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode
代码(github):https://github.com/illuz/leetcode
需要花费常数的空间。
Java:
Python:
Github: https://github.com/illuz/leetcode
003.Longest_Substring_Without_Repeating_Characters (Medium)
链接:
题目:https://oj.leetcode.com/problems/Longest-Substring-Without-Repeating-Characters/代码(github):https://github.com/illuz/leetcode
题意:
从标题就可以知道题意了,是求一个字符串中最长的不含重复字符的子串。分析:
开一个数组记录当前字符最近出现的位置,一遍算过去,更新左边界,用它计算最大值就行了。需要花费常数的空间。
代码:
C++:class Solution { public: int lengthOfLongestSubstring(string s) { int maxlen = 0, left = 0; int sz = s.length(); int prev ; memset(prev, -1, sizeof(prev)); for (int i = 0; i < sz; i++) { if (prev[s[i]] >= left) { left = prev[s[i]] + 1; } prev[s[i]] = i; maxlen = max(maxlen, i - left + 1); } return maxlen; } };
Java:
public class Solution { public int lengthOfLongestSubstring(String s) { int res = 0, left = 0; int prev[] = new int[300]; // init prev array for (int i = 0; i < 300; ++i) prev[i] = -1; for (int i = 0; i < s.length(); ++i) { if (prev[s.charAt(i)] >= left) left = prev[s.charAt(i)] + 1; prev[s.charAt(i)] = i; if (res < i - left + 1) res = i - left + 1; } return res; } }
Python:
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): res = 0 left = 0 d = {} for i, ch in enumerate(s): if ch in d and d[ch] >= left: left = d[ch] + 1 d[ch] = i res = max(res, i - left + 1) return res
相关文章推荐
- [LeetCode] 018. 4Sum (Medium) (C++/Java/Python)
- [LeetCode] 002. Add Two Numbers (Medium) (C++/Java/Python)
- [LeetCode] 015. 3Sum (Medium) (C++/Java/Python)
- [LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)
- [LeetCode] 017. Letter Combinations of a Phone Number (Medium) (C++/Java/Python)
- [LeetCode] 022. Generate Parentheses (Medium) (C++/Java/Python)
- [LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)
- [LeetCode] 011. Container With Most Water (Medium) (C++/Java/Python)
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- [LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)
- LeetCode 149 — Max Points on a Line(C++ Java Python)
- LeetCode 26 — Remove Duplicates from Sorted Array(C++ Java Python)
- LeetCode 63 — Unique Paths II(C++ Java Python)
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- LeetCode 15 — 3Sum(C++ Java Python)
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- LeetCode 62 — Unique Paths(C++ Java Python)
- LeetCode题解汇总(C++ Java Python,含题目翻译)