您的位置:首页 > 其它

LeetCode: Longest Substring Without Repeating Characters

2017-08-04 20:31 447 查看

题目:

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.

给定一个字符串,要求给出其最长无重复字符的子串的长度

给出
"abcabcbb"
, 符合要求的子串是
"abc"
, 长度是3.

给出
"bbbbb"
, 符合要求的子串是
"b"
, 长度是1.

给出
"pwwkew"
,符合要求的子串是
"wke"
, 长度是3. 注意答案要求的是子串,
"pwke"
 是一个子字符序列而并非子串.

思路:

假设有字符串a0,a1,a2,...,an,要求得他的最长无重复子串可以从a0开始,若a0,a1,...,ai 各不相同,那a0到ai的最长无重复子串就是他自己,我们把他的长度做一个备份s0,假定ai+1等于a0到ai中的一个元素aj,显然包含ai+1的最长无重复子串为aj+1,...,ai+1.故我们以aj+1为无重复子串的左端点继续向右,直到遍历整个字符串之后s0,s1,s2,...,sk,..中最大的值即为最长无重复字符的子串的长度。

代码

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256,-1);
int maxlength=0;int start=-1;
for(int i=0;i<s.size();i++){
if(dict[s[i]]>start)
start=dict[s[i]];
dict[s[i]]=i;
maxlength=max(maxlength,i-start);
}
return maxlength;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: