LeetCode Solutions
3. Longest Substring Without Repeating Characters
Time: $O(n)$ Space: $O(128) = O(1)$
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0;
vector<int> count(128);
for (int l = 0, r = 0; r < s.length(); ++r) {
++count[s[r]];
while (count[s[r]] > 1)
--count[s[l++]];
ans = max(ans, r - l + 1);
}
return ans;
}
};
class Solution {
public int lengthOfLongestSubstring(String s) {
int ans = 0;
int[] count = new int[128];
for (int l = 0, r = 0; r < s.length(); ++r) {
++count[s.charAt(r)];
while (count[s.charAt(r)] > 1)
--count[s.charAt(l++)];
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
ans = 0
count = Counter()
l = 0
for r, c in enumerate(s):
count[c] += 1
while count[c] > 1:
count[s[l]] -= 1
l += 1
ans = max(ans, r - l + 1)
return ans