地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/
题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
理解:
寻找没有重复字母的子串。暴力搜肯定是不可以的。
实现1:
注意一个性质,若s[i:j]有重复字母,则所有包含其的子串一定有重复。因此考虑所有两头相同的子串就可以了。
用一个hastset表示[i,j)
子串中的元素。其中[i,j)
子串一定是不含重复字符的。然后考虑s[j]
,如果s[j]
不在set中,就把j后移,并把s[j]
加入set,并更新最大子串的长度。如果已经在set中,就从i开始删除set中的元素,直到set中不包含s[j]
。当这样遍历完s
后,得到的就是最大长度。
复杂度分析:
- 时间复杂度:
O
(
2
n
)
=
O
(
n
)
O(2n)=O(n)
O(2n)=O(n)。最差的情况下,最后两个字母重复,每个字符都会被i和j遍历一次。最好的情况下没有重复,
i=0
,j=s.size()
。 - 空间复杂度: O ( m i n ( m , n ) ) O(min(m,n)) O(min(m,n))。其中 m m m为string字符集中字符的数目, n n n为string的长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> set;
int ans = 0, i = 0, j = 0;
while (i<s.size() && j<s.size()) {
if (!set.count(s[j])) {
set.insert(s[j++]);
ans = max(ans, j - i);
}
else
set.erase(s[i++]);
}
return ans;
}
};
实现2:
前面的实现中,出现重复,滑动窗的左边是递增的,直到删除了重复以后。也就是说在s[i,j)
的区间内,s[j']
和s[j]重复。但是中间这部分遍历其实是没有必要的,因为子串重复,比它更长的串肯定不符合要求。因此,可以直接从i=j'+1
开始考虑。用一个hashmap来存储下标。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> m;
int ans = 0;
for (int j = 0, i = 0; j < s.size(); ++j) {
if (m.count(s[j]))
//当i为大于m[s[j]]的值时,说明某个字母已经重复出现过了,i要保持最新
// i>m[s[j]] 可以理解为,中间的已经在上一个重复字母出现的时候被擦除了,i已经更新到了重复的字符后一个位置,更靠前的后重复的当然就不考虑了
i = max(m[s[j]], i);
ans = max(ans, j - i + 1);
m[s[j]] = j + 1;
}
return ans;
}
};
啊实现2竟然看了这么久。。太蠢了
注意当字符集数目有限的时候,下面的vector可以取代hashMap
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); i++) {
if (dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
更好理解,巧妙的用了start的取值,来代替m.count那一部分。
数组这部分的下标是真的恶心
困死。。看剧去了