您的位置:首页 > 其它

LeetCode-003 Longest Substring Without Repeating Characters

2017-09-13 17:18 387 查看

Description

Given a string, find the length of the longest substring without repeating characters.

Example

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.

Analyse

题目的意思很简单,就在一个字符串里找最长的没有重复字母的子串。其实这个题目可以转换为,求两个最近的相同字母的最大距离。那只需标记上一个相同字母的下标,然后若发现相同的时候,更新答案就行。

Code

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> charact(256,-1);
int start=-1,ans=0;
for (int i=0;i<s.length();i++) {
if (charact[s[i]]>start) {
start=charact[s[i]];
}//更新最近一个相同字母的位置
charact[s[i]]=i;//记录上一个字母的位置
if (i-start>ans) ans=i-start;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: