题目

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.

翻译

给定一个字符串,找到没有重复字符的最长子串的长度。

例子:

给定“abcabcbb”,答案是“abc”,长度为3。

给定“bbbbb”,答案是“b”,长度为1。

给定“pwwkew”,答案是“wke”,长度为3.请注意,答案必须是子字符串,“pwke”是子序列而不是子字符串。

Hints

Related Topics: Hash Table, Two Pointers, String

利用哈希表来存储字符的位置

计算以字符s结尾的子串的长度 需要一个指针来遍历string来获取每个字符s 还需要一个指针来表示当前以s结尾的子串的头部的位置

遇到之前出现过的字符时 表示上一个子串已经包含了s 需要重新计算头部 于是移动头部指针

参考

代码

Java

public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
int max = 0;
int start = 0;//表示现在用来计算最长子串的头的位置
Map<Character, Integer> mymap = new HashMap<>();//通过哈希表来存储现在某个字符出现的位置
for(int i=0;i<s.length();i++){
if(mymap.containsKey(s.charAt(i))){//现在这个字符在之前出现过
start = Math.max(start,mymap.get(s.charAt(i)+1);//需要把头移动到这个字符后面(头原来在上一个这个字符前面
}
mymap.put(s.charAt(i),i);//更新字符的位置
max = Math.max(max,i-start+1);//更新最长字串长度
}
return max;
}
}

Python

class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = maxlen = 0
mymap={}
for i in range(len(s)):
if s[i] in mymap:
start = max(start,mymap[s[i]]+1) maxlen = max(maxlen,i-start+1)
mymap[s[i]] = i
return maxlen

最新文章

  1. MySql学习(三) —— 子查询(where、from、exists) 及 连接查询(left join、right join、inner join、union join)
  2. 5,SFDC 管理员篇 - 数据模型 - 数据关联
  3. ACM题目————马拦过河卒
  4. codechef 两题
  5. LeetCode_Spiral Matrix
  6. dispatch_group_async
  7. mapxtreme演示V1.3
  8. Java IO学习笔记三
  9. JVM总结之内存区域
  10. xlsx导入成--json
  11. iOS----------YYModel
  12. Redux Todos Example
  13. 《精通python网络爬虫》笔记
  14. h5预加载代码
  15. 基础最短路(模板 dijkstra)
  16. VS2015 python
  17. Codeforces 1133 F2. Spanning Tree with One Fixed Degree 并查集+生成树
  18. C# 高级编程9 第30章MEF C#可扩展编程之MEF第2章(抄录)
  19. Solr调研总结(很详细很全面)
  20. 搭建Jenkins自动化持续构建和部署系统

热门文章

  1. Java ArrayList 源代码分析
  2. GC错误
  3. 在Titanic数据集上应用AdaBoost元算法
  4. Find the Duplicate Number (寻找重复数字)
  5. 基于 OpenResty 实现一个 WS 聊天室
  6. CH03 课下作业
  7. day 7 __new___
  8. 【bzoj4827】[Hnoi2017]礼物 FFT
  9. Windows server 2008 IIS7发布asp.net mvc网站css、js脚本无法访问 问题解决
  10. 《Node.js 包教不包会》