题目描述
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-substring-without-repeating-characters
滑动窗口
右指针移动,左指针查找,用length记录字串长度,用maxStr记录最大长度。
暴力循环
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.length() == 0) return 0;
int left = 0, maxStr = 0, length = 0;;
for (int right = 0; right < s.length(); ++right) {
// 查找重复元素
for (int j = left; j < right; ++j) {
if (s[right] == s[j]) {
left = j + 1;
length = right - left;
break;
}
}
++length;
maxStr = max(maxStr, length);
}
return maxStr;
}
};
hashmap优化
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
if (len == 0) return 0;
int left = 0, right = 0, leng = 0, maxStr = 0;
unordered_map<char, int> map;
for (right = 0; right < len; ++right) {
char tmpChar = s[right];
if (map.find(tmpChar) != map.end() && map[tmpChar] >= left) {
left = map[tmpChar] + 1;
leng = right - left;
}
map[tmpChar] = right;
++leng;
maxStr = max(maxStr, leng);
}
return maxStr;
}
};
桶优化
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
if (len == 0) return 0;
int tp[128], left = 0, right, maxStr = 0, length = 0;
memset(tp, -1, sizeof(tp));
for (right = 0; right < len; ++right) {
char tmpChar = s[right];
if (tp[(int)tmpChar] >= left) {
left = tp[(int)tmpChar] + 1;
length = right - left;
}
++length;
tp[(int)tmpChar] = right;
maxStr = max(maxStr, length);
}
return maxStr;
}
};