您的位置:首页 > 其它

leetcode 3. Longest Substring Without Repeating Characters

2017-06-23 11:41 513 查看



题目

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.



思路

L[i]表示当前最长不重复子串s[m..i],然后讨论L[i+1],显然有两种情况,当s[i+1],未出现过时,L[i+1]=s[m..i+1];当s[i+1] 出现过时,下标为K,更新m=max(k+1,m);

最大长度=max(logest,i-m+1),可以用ascii码将字符存在数组里

代码

int lengthOfLongestSubstring(string s) {
// for ASCII char sequence, use this as a hashmap
vector<int> charIndex(256, -1);
int longest = 0, m = 0;

for (int i = 0; i < s.length(); i++) {
m = max(charIndex[s[i]] + 1, m);
       charIndex[s[i]] = i;
longest = max(longest, i - m + 1);
}

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