给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
解题思路
执行用时:12 ms, 在所有 C++ 提交中击败了81.80% 的用户
内存消耗:7.1 MB, 在所有 C++ 提交中击败了100.00% 的用户
真的是无敌了,这个题目!
思路:
1.根ASCII表可以假设字符是有限的,这里我们可以用hash表的方式进行存储,每一个都初始化为-1
2.然后用两个变量len表示最大的不重复子串,current表示到当前位置的串的长度,两者找最大值,从而
更新len,
3.麻烦的地方有1:开始用idx=s[i] -'0'当成数字了,而后有改成了'a',没有考虑到特殊字符
4.更新current的时候注意当前值和之前值的差距,如果小于current,则current需要增大,如果小则把
current改小,不然对于输入为'abbba'的问题就会出错
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int data[128];
for(int i =0; i < 128; i++) {
data[i]= -1;
}
int len = 0;
int current = 0;
for(int i = 0; s[i] != '\0'; i++) {
int idx = s[i];
if(data[idx] == -1) {
current++;
data[idx] = i;
} else {
int len_c = i - data[idx];
if(len_c > current) current++;
else current = len_c;
data[idx] = i;
}
len = current > len ? current : len;
}
return len;
}
};