题目:无重复字符的最长子串
- 题号:3
- 难度:中等
- https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
实现
思路:借助动态规划的思路,从前到后求出以每个位置为终止位置,所构成无重复子串的长度,之后求这些长度的最大值即可。
对于任意位置index
其最长无重复子串的长度为result[index] = min{k1,k2}
,k1 = result[index-1] + 1
,k2
为从index
位置往前推直到出现index
位置的字符或index=0
为止的子串长度。
C# 语言
public class Solution
{
public int LengthOfLongestSubstring(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
int[] result = new int[s.Length];
result[0] = 1;
for (int i = 1; i < s.Length; i++)
{
int count = GetLength(i, s);
result[i] = result[i-1] < count ? result[i-1]+1 : count;
}
return result.Max();
}
private int GetLength(int index,string s)
{
char c = s[index];
int result = 1;
for (int i = index-1; i >= 0; i--)
{
if (s[i] != c)
result += 1;
else
break;
}
return result;
}
}
Python 语言
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
result = list()
result.append(1)
for i in range(1, len(s)):
count = self.GetLength(i, s)
result.append(result[i - 1] + 1 if result[i - 1] < count else count)
return max(result)
def GetLength(self, index, s):
c = s[index]
result = 1
for i in range(index - 1, -1, -1):
if s[i] != c:
result += 1
else:
break
return result