您的位置:首页 > 其它

leetcode lengthOfLongestSubstring

2016-03-07 16:37 281 查看
public static int lengthOfLongestSubstring(String s) {
boolean exit[]=new boolean[2024];
for(int i=0;i<1024;i++)
{
exit[i]=false;
}
if(s.length()==0)
{
return 0;
}
if(s.length()==1)
{
return 1;
}
int tail=0,head=1;
exit[s.charAt(tail)]=true;
int result=0;
int current=1;
while(head<s.length())
{
char c=s.charAt(head);
if(exit[c])
{
if(result<current)
{
result=current;

}

while(tail<s.length()&&s.charAt(tail)!=c)
{
exit[s.charAt(tail)]=false;

current--;
}
tail++;

}
else
{
exit[c]=true;
current++;

}
head++;
}
if(result<current)
{
result=current;
current=1;
}
return result;
}


牛人写的代码

思想是一样的

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> table(256, 0);
int maxstr=0, track=0;
for(int i=0;i<s.length();i++)
{
while(table[s[i]])table[s[track++]]=0;
table[s[i]]=1;
maxstr=max(maxstr, i-track+1);

}
return maxstr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: