您的位置:首页 > 其它

(算法分析Week19)Longest Substring Without Repeating Characters 最长无重复子串 [Medium]

2018-01-20 21:10 591 查看

3.Longest Substring Without Repeating Characters 最长无重复子串 [Medium]

[题目来源https://leetcode.com/problems/longest-substring-without-repeating-characters/description/)

Description

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.

Solution

求最长无重复子串。

用一个整型数组代替哈希表,然后遍历整个字符串,判断之前有没有遇到该字符。如果遇到,存储当下字符串的值,和max比较,看选哪个。然后从这个字符(第一次遇到)开始往后找。

Complexity analysis

O(n)

Code

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int m[256] = {0}, res = 0, left = 0;
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 0 || m[s[i]] < left) {
res = max(res, i - left + 1);
} else {
left = m[s[i]];
}
m[s[i]] = i + 1;
}
return res;
}
};


Result

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