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) {
if(s.empty())
return 0;
int i=0,j,count=0,max=0;
for(j=0;j<s.size();j++){
for(int k=i;k<j;k++)
if(s[k]==s[j]){
count=j-i;
max=count>max?count:max;
i=k+1;
break;
}
}
count=j-i;
max=count>max?count:max;
return max;
}
};
方法二:犧牲空間的方法去,提高搜索時間效率,時間複雜度O(n)。類似於關聯數組,map。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int locs[256];
memset(locs, -1, sizeof(locs));
int idx = -1, max = 0;
for (int i = 0; i < s.size(); i++)
{
if (locs[s[i]] > idx)
{
idx = locs[s[i]];
}
if (i - idx > max)
{
max = i - idx;
}
locs[s[i]] = i;
}
return max;
}
};