您的位置:首页 > 其它

LeetCode 3 : Longest Substring Without Repeating Characters ---- 不重复的子串

2016-05-18 14:21 411 查看
原题链接: https://leetcode.com/problems/longest-substring-without-repeating-characters/
一:原题内容

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 asubstring,
"pwke"
is a
subsequence and not a substring.

二:AC代码

class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
int flag[128]={0};
int ans=0;//the answer
int j=0;

for(int i=0;i<s.size();i++)
{
if(flag[s[i]]>0)
{
j=max(j,flag[s[i]]);
}

flag[s[i]]=i+1;
ans=max(ans,i-j+1);
}

return ans;
}
};


class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""

ret=0
left=0
d={}

for index,value in enumerate(s):
if value in d and d[value]>=left:
left=d[value]+1

d[value]=index
ret=max(ret,index-left+1)
return ret

返回LeetCode 题解目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: