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.
代码:
class Solution{
public:
int lengthOfLongestSubstring(string s)
{
int longlength=0;
map<int,string> imap;
typedef string::size_type st;
typedef map<int,string>::iterator itmap;
string substr;
for(st ix=0;ix!=s.size();++ix)
{
for(st iy=ix+1;iy!=s.size()+1;++iy)
{
substr=s.substr(ix,iy-ix);
if(substr.find(s[iy])<10000)//没有找到特定字符时返回的迭代器很大,我以10000为界
{
substr.erase(iy-ix);
break;
}
}
imap.insert(map<int,string>::value_type(substr.size(),substr));
}
for(itmap iter=imap.begin();iter!=imap.end();++iter)
{
if(iter->first>longlength)
longlength=iter->first;
}
return longlength;
}
};
时间复杂度最差为O(n2),空间复杂度为O(n)。
看了一下intuition,我的做法不是第一种brute force ,类似于第二种的sliding window。不过提供的第三种解法并没有看懂。
sliding window称为滑动窗口,经常应用于array和string 问题求解中。例如:给定一个array为[1,4,5,2,7,4,8,3,0,9],找寻最大值,对象长度n为10,设窗口长度k为3。则:第一个窗口为[1,4,5],最大值为5,第二个窗口为[4,5,2],最大值为5…….最后一个窗口n-k+1为[3,0,9],最大值为9.
思路我想大多数人都能想到,具体关于算法的应用可自行搜索。