每日算法——letcode系列
問題 Longest Substring Without Repeating Characters
Difficulty: Medium
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
}
};
翻譯
無重復(fù)字符的最長子串
難度系數(shù):中等
給定一個字符串,找其無重復(fù)字符的最長子串的長度。
例如: "abcabcbb"的無重復(fù)字符的最長子串是"abc",長度為3。 "bbbbb"的無重復(fù)字符的最長子串是"b",長度為1
思路
方案一:
遍歷字符串,如果前面有重復(fù)的,就把前面離現(xiàn)在這個字符最近的重復(fù)的字符的索引記錄在repeatIndex, 如果沒有重復(fù),則也為repeatIndex。
注意: 當(dāng)前的repeatIndex要大于以前記錄的repeatIndex,小于則不更新repeatIndex下面第三種情況
如:
"abcabcbb" -> $\frac{abcabcbb}{00012357}$ -> $\frac{12345678}{00012357}$ -> 3
"bbabcdb" -> $\frac{bbabcdb}{0112224}$ -> $\frac{1234567}{0112224}$ -> 4
"abba" -> $\frac{abba}{0022}$ -> $\frac{1234}{0022}$ -> 2
方案二:
找重復(fù)的時候可以用hashmap的方法來降低時間復(fù)雜度, string的字符為key, 索引為value。
代碼
方案一:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0;
int repeatIndex = 0;
int size = static_cast<int>(s.size());
for (int i = 0; i < size; ++i){
for (int j = i - 1; j >= 0; --j) {
if (s[i] == s[j]){
if (j > repeatIndex){
repeatIndex = j;
}
break;
}
}
if (maxLen < i -repeatIndex){
maxLen = i - repeatIndex;
}
}
return maxLen;
}
}
方案二:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0;
int repeatIndex = 0;
int size = static_cast<int>(s.size());
map<char, int> tempHash;
for (int i = 0; i < size; ++i){
if (tempHash.find(s[i]) != tempHash.end() && tempHash[s[i]] > repeatIndex){
repeatIndex = tempHash[s[i]];
}
if (maxLen < i -repeatIndex){
maxLen = i - repeatIndex;
}
tempHash[s[i]] = i;
}
return maxLen;
}
}