給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。
示例 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;
}
};