您的位置:首页 > 其它

LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium

2017-12-08 11:28 716 查看

题目:

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.

问题解析:

给定一个字符串,从中找出不含重复字符的最长子串的长度。

链接:

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

思路标签:

算法:DP

数据结构:Vector

解答:

1. C++

假设L[i] = s[start … i],表示最长的子字符串,其中没有重复的元素,我们以Vector作为hashmap保存< 字符,索引>;

然后访问s[i + 1]:

1)如果s[i + 1]没有出现在散列表dict中,我们可以将s[i + 1]添加到散列表中,则有L[i + 1] = s[start … i + 1];

2)如果s[i + 1]存在于dict中,并且dict中对应的索引是k;则令start = max(start,k),则L[i + 1] = s[start … i + 1],记录此时的最大长度;

整个问题就是围绕不加入重复元素而展开的。

时间复杂度:O(n)

class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1);
int maxLen = 0, start = -1;
for (int i = 0; i != s.length(); ++i) {
if (d
4000
ict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};


2. python

class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = maxLength = 0
usedChar = {}

for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1
else:
maxLength = max(maxLength, i - start + 1)

usedChar[s[i]] = i

return maxLength


算法相关

动态规划:https://www.zhihu.com/question/23995189

C++相关:

max方法依赖:
#include <algorithm>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode DP Hash vector
相关文章推荐