博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 3. Longest Substring Without Repeating Characters(无重复最长子串) 解法 python
阅读量:2490 次
发布时间:2019-05-11

本文共 1237 字,大约阅读时间需要 4 分钟。

这道题去年用java写过一次,回头看感觉不堪入目,哈哈,这次用python再做一遍

一.问题描述

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"Output: 3 Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: "bbbbb"Output: 1Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"Output: 3Explanation: 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.

二.解题思路

这道题一开始想想以为是动态规划,但是仔细一想不满足动态规划的无后效性的原则,即我如何达到当前状态的历史信息会影响我下一判断的决策

解这道题就遍历一遍字符串,然后用一个字符串保存之前的迭代的不重叠子串(我用begin和end来替换开一个字符串保存,用这种方式运行会快几ms,从76ms->68ms)和记录长度,如果当前字符在保存的子串中有

说明现在保存的字串已经达到了它的最大不重叠长度,然后比较它的长度是否大于我们之前保存的最大长度,更新最大长度

然后将不重叠子串更新一下,更新为从上一个重叠字符的下一个字符开始到现在迭代的字符(因为我们只需要将上一个重叠的字符去掉之后,它又变成了一个不重叠的字符串)。迭代结束就出结果了。

更多leetcode算法题解法请关注我的专栏或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:    def lengthOfLongestSubstring(self, s: str) -> int:        if s=='': return 0        maxlen,begin,end=1,0,0        for k in range(1,len(s)):            index=s.find(s[k],begin,end+1)            if index!=-1:                maxlen=max(maxlen,end-begin+1)                begin=index+1               end+=1        return max(maxlen,end-begin+1)

 

转载地址:http://oqmrb.baihongyu.com/

你可能感兴趣的文章
LNMP 安装 thinkcmf提示404not found
查看>>
PHP empty、isset、innull的区别
查看>>
apache+nginx 实现动静分离
查看>>
通过Navicat远程连接MySQL配置
查看>>
phpstorm开发工具的设置用法
查看>>
Linux 系统挂载数据盘
查看>>
Git基础(三)--常见错误及解决方案
查看>>
Git(四) - 分支管理
查看>>
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
PHP 实现笛卡尔积
查看>>
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>