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.
1.o(n)时间复杂度的算法
class Solution { public: int lengthOfLongestSubstring(string s) { int sSize = s.size(); if(sSize ==0){ return 0; } int smap[260]={0};//smap存储的是字符s[i]的位置加1,加1是为了区别字符不存在的情况,字符不存在时,smap值为0 smap[s[0]] = 1; int winStart = 0,winEnd = 1;//滑动窗口的首末位置 int winMax = 1; for(int i=1;i<sSize;i++){ int index = smap[s[i]]-1; if(index >=0 ){//说明s[i]字符存在,滑动窗口减小 for(int i=winStart;i<=index;i++){ smap[s[i]] = 0; } winMax = max(winEnd-winStart,winMax); winStart = index+1; } smap[s[i]] = i+1; winEnd = i+1; } winMax = max(winEnd-winStart,winMax); return winMax; } };
2.o(nlgn)时间复杂度的算法
其实这题也可以用二分的思想来做,题目求的最大连续不存在重复元素的长度,这个长度最大是字符串s的长度,最小是0,我们可以用二分,开始假设结果是字符串长度的一半,
然后把滑动窗口设置为这个长度,检验是否存在长度为其的连续串,根据结果设定low,high的值。
代码比较简单,就不写了,可以参考下面这题:
时间: 2024-11-03 11:32:16