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

首先我解这个题的思路是依次找到一个字符串的所有字串,和已存的LongestSubstring比较长度,如大于,替换,直至找到所有的字串。

我的这个程序可能还有问题,提交后显示为Time Limit Exceeded(超时),不过我有时间会改下它,找到错误。

 class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longestSubstring = ''
strLength = len(s)
longestSubstringLength = 0
for i in range(strLength):
subString = ''
str = s[i:strLength]
for j in range(len(str)):
if str[j] not in subString:
subString += str[j]
if j == len(str)-1:
substringLength = len(subString)
if substringLength>longestSubstringLength:
longestSubstringLength = substringLength
longestSubstring = subString
else:
substringLength = len(subString)
if substringLength>longestSubstringLength:
longestSubstringLength = substringLength
longestSubstring = subString
break
return longestSubstringLength

在网上我找到了另外的对于Python特别方便的解法:开一个字典记录字符串中的字符和它的索引,left用来记录当前字符最新出现的地方。

 class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
left = 0
d = {}
for i,ch in enumerate(s):
if ch in d and d[ch] >= left:
left = d[ch] + 1
d[ch] = i
res = max(res,i - left + 1)
return res

最新文章

  1. What does "size" in int(size) of MySQL mean?
  2. @SuppressWarnings("finally")
  3. jquery制作弹出层带遮罩效果,点击阴影部分层消失
  4. python反射机制深入分析
  5. 系统上线后WCF服务最近经常死掉的原因分析总结
  6. Python 编程规范-----转载
  7. Android编程: 调试方法
  8. Java 字符转码之UTF-8转为GBK/GB2312
  9. 锱铢必较,从(function(){}())与(function(){})()说起
  10. 如何获取App当前版本号
  11. Linux 杀死挂起的进程
  12. avalon - 初步接触
  13. 解读JavaScript原型链
  14. javascript类型判断方法
  15. POJ 1159 Palindrome(最长公共子序列)
  16. Using Java in Debian
  17. 使用fckeditor上传多张图片
  18. python-状态模式
  19. Spring Boot整合MyBatis(使用Spring Tool Suite工具)
  20. ubuntu 常用命令集锦

热门文章

  1. Contiki学习笔记  第一个程序:Hello World
  2. Ubuntu14.04用apt在线/离线安装CDH5.1.2[Apache Hadoop 2.3.0]
  3. Linux常用的安全工具 转自https://yq.aliyun.com/articles/52540?spm=5176.100239.blogcont24250.8.CfBYE9
  4. SQL Server 开发-语法学习
  5. IQueryable join 的问题
  6. C# dataTable 排序
  7. 【转载】Keil中的USE MicroLib说明
  8. 黄聪:GeckoFX如何引用jquery文件并执行自定义JS
  9. 在阿里云主机上基于CentOS用vsftpd搭建FTP服务器
  10. Blink Without Delay: 不使用 delay() 函数而使 LED 闪烁