Leetcode中等:3. 无重复字符的最长子串

题目:无重复字符的最长子串

  • 题号: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] + 1k2为从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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青少年编程小助手_Python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值