[LeetCode] 003. Longest Substring Without Repeating Characters (Medium) (C ++/Java/Python), leetcoderepeating
Index: [LeetCode] Leetcode index (C ++/Java/Python/SQL)
Github: https://github.com/illuz/leetcode
003. Longest_Substring_Without_Repeating_Characters (Medium)
Link:
Title: https://oj.leetcode.com/problems/Longest-Substring-Without-Repeating-Characters/
Code (github): https://github.com/illuz/leetcode
Question:
From the title, you can understand the meaning of the question. It is to find the longest substring in a string that does not contain repeated characters.
Analysis:
Open an array to record the location where the current character has appeared recently. Calculate it again, update the left boundary, and use it to calculate the maximum value.
Space that requires constant.
Code:
C ++:
class Solution {public: int lengthOfLongestSubstring(string s) { int maxlen = 0, left = 0; int sz = s.length(); int prev[N]; 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