原题:
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.
大意:
给你一个字符串,让你找出这个字符串中的一个最长的子串,这个子串要满足的条件是没有重复的字符。
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int mark[300];
fill(mark,mark+300,-1);
int ans=0,tmp=0,pre=0;
for(int i=0;i<s.size();i++)
{
if(mark[s[i]-' ']!=-1)
{
pre=max(pre,mark[s[i]-' ']+1);
}
mark[s[i]-' ']=i;
ans=max(ans,i-pre+1);
}
return ans;
}
};
解答:
利用尺取法,用一个hash记录之前找到的的字母的最远位置,每次搜索到新的字母时,判断该字母是否出现过,如果没出现过,那么长度加一,否则标尺左侧右移到当前字符的下一个位置即可。时间复杂度o(n)