Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", which the length is 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.
Solution1 26ms
建一个map<char,int>滑动窗口,对每一个end位置,调整start位置,使得map中的数值小于等于1
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> cmap;
int start = 0;
int length;
int length_max=0;
for (int i =0;i<s.length();i++)
{
char c = s[i];
if(cmap.find(c)!=cmap.end()){cmap[c]++;}
else{cmap[c]=1;}
while(cmap[c]>1){
char ctmp = s[start];
cmap[ctmp] --;
start++;
}
length = i-start+1;
length_max = length>length_max?length:length_max;
}
return length_max;
}
};
Solution2 16ms
建一个256维的int数组,数组中的int * idx(0-256)代表char类型的256种字符,idx处存储的int 值表示自end往前,上一次遇到该字符的位置,如果在idx处再遇到同样的字符,那就把窗口的start设为该字符上一次遇到的位置
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> map(256,-1);
int start = -1;
int maxlength =0;
for(int i = 0;i<s.length();i++){
if(map[s[i]]>start){
start = map[s[i]];
}
map[s[i]]=i;
maxlength = max(maxlength,i-start);
}
return maxlength;
}
};
Note
加上下面一段代码,solution1 速度可以提升到16ms,solution2速度可以提升到8ms
static const auto io_sync_off = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
网上的解释:
一般情况下不用函数库优化的话,大数据输入输出c语言比c++快一倍多,运行效率也会高一些这是c语言更接近低端语言,容易识别 你应该是初学吧,很多地方要用函数优化c++才会体现它的优越性 比如cin在#include <algorithm>头文件下 主函数中+入 std::ios::sync_with_stdio(false) 会大幅提高效率,最后会比scanf还快0.5倍 cin慢在它输入时与stdin同步,尤其是在文件输入输出时特别慢 但关闭同步功能后马上速度就快了