leetcode 3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.
思路:用map维护区间内各个字母的数量,然后遇到已经访问过的就进行滑动区间,来得到符合条件的区间,然后求最大区间长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0;
int l = 0;
unordered_map<char, int> mp;
for (int i = 0; i < s.size(); ++i) {
if (!mp[s[i]]) ++mp[s[i]];
else {
while (l < i && mp[s[i]] > 0) {
--mp[s[l]];
++l;
}
mp[s[i]] = 1;
}
ans = max(ans, i - l + 1);
}
return ans;
}
};
虽然时间复杂度是O(n)但是感觉比最好的代码还是慢了点。
这个代码可以改进一下,首先不用 unordered_map做为映射结构,用vector<int>v(256)
256是ASII表的大小。字母表先初始话为-1,然后用l表示s[i]上一次出现的位置,具体实现见代码。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
int ans = 0;
vector<int> v(256, -1);
int l = -1;
for (int i = 0; i < s.size(); ++i) {
if (v[s[i]] > l) l = v[s[i]];
v[s[i]] = i;
ans = max(ans, v[s[i]] - l);
}
return ans;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: