题目: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.
题意:就是寻找一个给定字符串中的不重复最长字串的长度。比如abcdab,最长的串位abcd或cdab,长度位4.
这道题中,首先,想到是字符串,然后就可以想到用255大小的桶来标记下标对应的字母是否出现过,即cnt[255],然后想到用hash表,用一个hash table保存每个字符上一次出现过的位置,即vis[255]。从前往后扫描,假如发现字符上次出现过,就把当前子串的起始位置start移动到上次出现过的位置之后——这是为了保证从start到i的当前子串中没有任何重复字符。同时,由于start移动,当前子串的内容改变,start移动过程中经历的字符都要剔除。
class Solution {
public:
int max(int a,int b)
{
return a>b?a:b;
}
int lengthOfLongestSubstring(string s) {
int len=s.length();
int cnt[256]={0};
int vis[256]={0};
int i,j;
int start=0;
int Max=0;
for(i=0;i<len;i++)
{
if(!cnt[s[i]])
{
cnt[s[i]]=1;
vis[s[i]]=i;
Max=max(Max,i-start+1);
}
else
{
Max=max(Max,i-vis[s[i]]);
for(j=start;j<=vis[s[i]];j++)
{
cnt[s[j]]=0;
}
start=vis[s[i]]+1;
vis[s[i]]=i;
cnt[s[i]]=1;
}
}
return Max;
}
};
这次排名相当不错啊