题目:
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.
思路:
典型的字符串问题中的“Two Pointers”的应用。可以借助一个hash表,维护一个不包含重复字符串的窗口,使用左右指针left,right滑动窗口大小。左右指针的滑动规则如下:
1)首先右指针right向右移动,直到遇到一个和窗口中有重复的字符。右指针在滑动过程中更新最大不重复子串的长度。
2)此时左指针向右移动到重复字符之后去,同时更新hash表中的字符。
该算法的时间复杂度为O(n),空间复杂度依然为O(n)。
在面试中需要注意英文中“subsequence”和“substring”的区别。前者中的邻接字符在原串中也必须是邻接的,而后者中的邻接字符在原串中未必需要邻接。
代码:
C++:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() == 0)
return 0;
int left = 0, right = 0, max_length = 0;
unordered_map<char, bool> hash;
for(right = 0; right < s.size(); ++right)
{
while(hash.count(s[right]))
hash.erase(s[left++]);
hash[s[right]] = true;
max_length = max(max_length, (int)hash.size());
}
return max_length;
}
};
Python3:
class Solution:
def lengthOfLongestSubstring(self, s: 'str') -> 'int':
if len(s) == len(set(s)): # this means every charchater is unique
return len(s)
d = {} # map from values to indices
start = 0
tmp = 0
ans = 0
for index, val in enumerate(s):
if val in d and d[val]>= start:
start = d[val] + 1
d[val] = index
tmp = index - start + 1
ans = max(ans,tmp)
return ans
本文介绍了一种利用双指针技巧寻找字符串中最长无重复字符子串的方法,并提供了C++与Python实现代码。通过滑动窗口的方式,结合哈希表来记录字符出现的位置,有效地解决了这一经典问题。
566

被折叠的 条评论
为什么被折叠?



