题目描述
给定一个字符串 s 和一个字符集合 charSet,要求找到字符串 s 中不包含 charSet 中任何字符的最长子字符串的长度。
输入:
- 字符串 s(仅包含小写字母)
- 字符集合 charSet(一个字符串,包含若干个不同的小写字母)
输出:
- 返回字符串 s 中不包含 charSet 中任何字符的最长子字符串的长度。
示例:
输入:s = "abcabcbb", charSet = "abc"
输出:3
解释:最长的不包含 "a", "b", "c" 的子字符串是 "bb",长度为 3。
解题思路
- 初始化变量:
- maxLength 用于记录最长子字符串的长度,初始化为 0。
- currentLength 用于记录当前正在考察的子字符串的长度,初始化为 0。
- charSetSet 用于快速判断一个字符是否在 charSet 中,初始化为 charSet 的字符集合。
- 遍历字符串 s:
- 对于每一个字符 c,检查它是否在 charSetSet 中。
- 如果 c 不在 charSetSet 中,则 currentLength 增加 1。
- 如果 c 在 charSetSet 中,则更新 maxLength 为 currentLength 和 maxLength 的较大值,并将 currentLength 重置为 0。
- 处理最后一个子字符串:
- 遍历结束后,还需要检查并更新 maxLength,因为最后一个子字符串可能是最长的。
Java 编码解析
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int longestSubstringWithoutCharSet(String s, String charSet) {
Set<Character> charSetSet = new HashSet<>();
for (char c : charSet.toCharArray()) {
charSetSet.add(c);
}
int maxLength = 0;
int currentLength = 0;
for (char c : s.toCharArray()) {
if (!charSetSet.contains(c)) {
currentLength++;
} else {
maxLength = Math.max(maxLength, currentLength);
currentLength = 0;
}
}
maxLength = Math.max(maxLength, currentLength);
return maxLength;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.longestSubstringWithoutCharSet("abcabcbb", "abc")); // 输出 3
}
}
C++ 编码解析
#include <iostream>
#include <unordered_set>
#include <string>
#include <algorithm>
using namespace std;
int longestSubstringWithoutCharSet(const string& s, const string& charSet) {
unordered_set<char> charSetSet(charSet.begin(), charSet.end());
int maxLength = 0;
int currentLength = 0;
for (char c : s) {
if (charSetSet.find(c) == charSetSet.end()) {
currentLength++;
} else {
maxLength = max(maxLength, currentLength);
currentLength = 0;
}
}
maxLength = max(maxLength, currentLength);
return maxLength;
}
int main() {
string s = "abcabcbb";
string charSet = "abc";
cout << longestSubstringWithoutCharSet(s, charSet) << endl; // 输出 3
return 0;
}
Python 编码解析
def longestSubstringWithoutCharSet(s: str, charSet: str) -> int:
charSetSet = set(charSet)
max_length = 0
current_length = 0
for c in s:
if c not in charSetSet:
current_length += 1
else:
max_length = max(max_length, current_length)
current_length = 0
max_length = max(max_length, current_length)
return max_length
# 测试
s = "abcabcbb"
charSet = "abc"
print(longestSubstringWithoutCharSet(s, charSet)) # 输出 3