博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode之Longest Substring Without Repeating Characters
阅读量:4131 次
发布时间:2019-05-25

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

原题描述

3.Longest Substring Without Repeating Characters

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.

解题思路

遍历字符串,用一个容器存放已读的字符,用来判断是否存在重复字符,用一个max记录当前下最大的不重复子串长度。对于"abcb"这种,到了第二个b的时候,可以发现两个b之间是不可能有不重复子串的,所以新的子串要从c处开始记录即b.index+1处,用start记录子串的新起点,为了防止出现“abcba”这种b的重复先出现了后,将新start设为2了,下次a出来以后start再给设为1,要在原start和新start之间取最大值。容器选用map<Character, Integer>对应子串中每个字符的index。这样遍历一遍后得的max即为结果
public int lengthOfLongestSubstring(String s) {        int max = 0;int start = 0;        Map
map = new HashMap(); for(int i = 0;i < s.length();i++){ if(map.containsKey(s.charAt(i))){ start = Math.max(map.get(s.charAt(i)) + 1,start); } max = Math.max(max,i-start+1); map.put(s.charAt(i),i); } return max; }

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

你可能感兴趣的文章
自己的网站与UCenter整合(大致流程)
查看>>
laravel 制作通用的curd 后台操作
查看>>
【小红书2017年笔试】求一个数组中平均数最大的子数组
查看>>
Linux基础系列-定时器与时间管理
查看>>
Linux基础系列-可执行程序的产生过程
查看>>
Linux基础系列-Kernel 初始化宏
查看>>
Linux子系统系列-I2C
查看>>
<iOS>关于自定义description的一点用法
查看>>
Unix 命令,常用到的
查看>>
DLL中建立进程共享数据段需要注意的语法问题
查看>>
服务器端技术----Http请求的处理过程
查看>>
C语言-预处理指令2-条件编译
查看>>
C语言-预处理指令3-文件包含
查看>>
C语言-变量类型
查看>>
C语言-static和extern关键字1-对函数的作用
查看>>
C 语言-static和extern关键字2-对变量的作用
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
还不会正则表达式?看这篇!
查看>>
100道+ JavaScript 面试题,助你查漏补缺
查看>>
JavaScript深入理解之闭包
查看>>