3Longest Substring Without Repeating Characters,longestrepeating
分享于 点击 17114 次 点评:191
3Longest Substring Without Repeating Characters,longestrepeating
3 Longest Substring Without Repeating Characters
题目
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 flag[500]={0};
const char * p;
p = s.c_str();
int i=0,j=0;
int ans=0;
int tmp=0;
flag[p[i]]=1;
if(p[0]=='\0')
return 0;
if(p[1]=='\0')
return 1;
for (j = 1; j < s.length(); j++)
{
if(flag[p[j]]==1)
{
while(p[i]!=p[j])
{
flag[p[i]] = 0;
i++;
}
flag[p[i]] = 0;
i++;
flag[p[j]] = 1;
tmp = j-i+1;
if(tmp>ans)
ans=tmp;
}
else{
flag[p[j]]=1;
tmp = j-i+1;
if(tmp>ans)
ans=tmp;
}
}
return ans;
}
};
小结
基本o(n)方法,其实flag可以用hashmap或者map,但是由于字母也没多少个,就用flag了。
相关文章
- 暂无相关文章
用户点评