蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]

题目

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.

翻译

给定一个字符串,找到没有重复字符的最长子串的长度。

例子:

给定“abcabcbb”,答案是“abc”,长度为3。

给定“bbbbb”,答案是“b”,长度为1。

给定“pwwkew”,答案是“wke”,长度为3.请注意,答案必须是子字符串,“pwke”是子序列而不是子字符串。

Hints

Related Topics: Hash Table, Two Pointers, String

利用哈希表来存储字符的位置

计算以字符s结尾的子串的长度 需要一个指针来遍历string来获取每个字符s 还需要一个指针来表示当前以s结尾的子串的头部的位置

遇到之前出现过的字符时 表示上一个子串已经包含了s 需要重新计算头部 于是移动头部指针

参考

代码

Java

public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
int max = 0;
int start = 0;//表示现在用来计算最长子串的头的位置
Map<Character, Integer> mymap = new HashMap<>();//通过哈希表来存储现在某个字符出现的位置
for(int i=0;i<s.length();i++){
if(mymap.containsKey(s.charAt(i))){//现在这个字符在之前出现过
start = Math.max(start,mymap.get(s.charAt(i)+1);//需要把头移动到这个字符后面(头原来在上一个这个字符前面
}
mymap.put(s.charAt(i),i);//更新字符的位置
max = Math.max(max,i-start+1);//更新最长字串长度
}
return max;
}
}

Python

class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = maxlen = 0
mymap={}
for i in range(len(s)):
if s[i] in mymap:
start = max(start,mymap[s[i]]+1) maxlen = max(maxlen,i-start+1)
mymap[s[i]] = i
return maxlen
上一篇:Longest Substring Without Repeating Characters(Difficulty: Medium)


下一篇:3. Longest Substring Without Repeating Characters - 最长无重复字符子串-Medium