LeetCode题解专栏:LeetCode题解
LeetCode 所有题目总结:LeetCode 所有题目总结
大部分题目C++,Python,Java的解法都有。
题目地址:Longest Substring with At Most Two Distinct Characters - LeetCode
Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
这道题目是hard难度的,题目的意思很简单,就是找到具有最多两个不同字符的最长子串的长度。
看到题目会感觉O(n)的时间复杂度应该能做出这道题目。
在写了大约20分钟代码后,Python解法出来了:
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
count = 0
p = {
}
l = {
}
for now in range(0, len(s)):
i = s[now]
p[i] = now
if len(l) < 2 and i not in l:
l[i] = 1
elif i in l:
l[i] += 1
else:
if count < sum(l.values()):
count = sum(l.values())
for j in l.keys():
if j != s[now-1]:
l.pop(j)
l[list(l.keys())[0]] = now-p[j]-1
break
l[i] = 1
if l != {
}:
if count < sum(l.values()):
count = sum(l.values())
return count
我的解法稍微有点麻烦,但易懂,最快解法如下:
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
i, l, k = -1, 0, 0
for j in range(1, len(s)):
if s[j] != s[j-1]:
if i > -1 and s[i] != s[j]:
l, k = i+1, max(k, j-l)
i = j-1
return max(k, len(s)-l)
核心思路跟我的做法一样。
区别在于它使用i和j来跟踪两个字符的最后一个索引。i跟踪第一个字符,j跟踪第二个字符。但我仍然喜欢hashmap解决方案,因为我们可以轻松地将该解决方案扩展到K个不同的字符。
C++解法如下:
class Solution
{
public:
int lengthOfLongestSubstringTwoDistinct(string s)
{
int i = 0, j = -1;
int maxLen = 0;
for (int k = 1; k < s.size(); k++)
{
if (s[k] == s[k - 1])
continue;
if (j > -1 && s[k] != s[j])
{
maxLen = max(maxLen, k - i);
i = j + 1;
}
j = k - 1;
}
return maxLen > (s.size() - i) ? maxLen : s.size() - i;
}
};
其他人的Java解法如下:
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String str) {
int i = 0, j = -1;
int maxLen = 0;
char[] s = str.toCharArray();
for (int k = 1; k < s.length; k++) {
if (s[k] == s[k - 1])
continue;
if (j > -1 && s[k] != s[j]) {
maxLen = Math.max(maxLen, k - i);
i = j + 1;
}
j = k - 1;
}
return maxLen > (s.length - i) ? maxLen : s.length - i;
}
}