Leetcode Longest Substring Without Repeating Characters
来源:互联网 发布:php对象的作用 编辑:程序博客网 时间:2024/05/18 04:05
题目:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
问题描述:在字符串中寻找最长无重复的子串,返回其最大长度
解题方法描述:
转载:http://blog.csdn.net/likecool21/article/details/10858799
因为字符的Ascii码值是唯一的,因此可以建立一个数组,数组的下标表示这个字符的ASCII码,范围为0-255,则可设置数组大小为256,数组中元素表示其在字符串中的位置。寻找的过程为:逐个便利字符,将字符的位置存入其对应的ASCII下标下,当遇到和之前重复的字符(前一次出现称为Occur 1, 这一次出现称为Occur 2)时,即遇到了一个可能的最大值;进行比较后,将下一次扫描的起点设置为刚才这个重复字符的Occur 1的后一位即可。表示如图:
Python 代码如下:
用列表实现数组,初始化为-1.
由c++程序翻译的,估计有更简单的Python写法,有待继续改进。
Leetcode 的Python 环境中不支持中文注释。
真正编程时如果想用中文字符,在文件开始出加入:# -*- coding: cp936 -*-
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): l=len(s) if l<=1: return l dic=[-1,]*256 #数组初始化 start=0 res=0 i=0 for i in range(0,l): if dic[ord(s[i])]!=-1: #元素已经存在 则可能有最大长度 res=max(res,i-start) for j in range(start,dic[ord(s[i])]): #将重复部分清空 dic[ord(s[j])]=-1 if dic[ord(s[i])]+1>start: #开始位置设为重复位置的下一位 start=dic[ord(s[i])]+1 dic[ord(s[i])]=i else: dic[ord(s[i])]=i res=max(res,l-start) return res
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- UVa 10014 - Simple calculations
- zzuli 1432 背包again(求最小不能被得到的价值
- STL中vector删除一个元素
- POJ 3561
- 对Java中多态的认识总结
- Leetcode Longest Substring Without Repeating Characters
- 数字到字符串、字符串到数字的转换
- 阶乘
- Java中尽量使用StringBuilder和StringBuffer进行字符串连接
- java环境变量
- 王达大讲堂视频课程会员优惠购买方案
- 在云计算中实现安全、可伸缩、细粒度数据的访问控制
- 核心卷I笔记 集合
- SEO学习笔记二(SEO实战密码读书笔记)