【leetcode】3. Longest Substring Without Repeating Characters 【medium】

来源:互联网 发布:淘宝天猫店铺转让 编辑:程序博客网 时间:2024/05/16 09:45

题目:

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.

Subscribe to see which companies asked this question

解题思路:

用一个bool数组标记一个字符是否出现过,这个数组至少大于256吧。然后使用两个指针i,j,都从零开始向后扫,但j指针一开始是不动的,是要等

s[i]==s[j],然后j指针扫描从j到i之间是哪个字符重复出现过。那么此时最短不重复字符串就是i-j+1.因为i一直向后走,所以不断更新这个最短字符串的长度就行了。


代码:

class Solution {
public:
int lengthOfLongestSubstring(string s) {
bool m[300]={0};

int c=0;int j=0,i=0;
for(i;i<s.size(); i++)
{
// cout<<i<<endl;
if(m[s[i]]==0)
{
m[s[i]]=1;

}

else
{

for(j;j<i;j++)
{

if(s[j]==s[i])
{

j++;
break;
}
else
{
m[s[j]]=0;
}

}

}
c=max(c,i-j+1);

}

return c;
}
};

0 0
原创粉丝点击