3. Longest Substring Without Repeating Characters
2016-05-14 14:52
453 查看
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
which the length is 3.
Given
with the length of 1.
Given
with the length of 3. Note that the answer must be a substring,
a subsequence and not a substring.
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.
public class Solution { public int lengthOfLongestSubstring(String s) { int[] last = new int[128]; int start = 0; int len = 0; char[] w = new char[s.length()]; w = s.toCharArray(); for(int i = 0; i < 128; i++) last[i] = -1;//last数组用于保存新出现的字符的下标,一开始全部初始化为-1 for(int i = 0; i < s.length(); ++i){ if(last[w[i]-' '] >= start){ //当前这个字符出现过 if(i-start > len) len = i-start; start = last[w[i]-' '] + 1; //从这个字符首次出现的位置+1,重新扫描,相当于把前面抛开前面的字符串不谈 } last[w[i]-' '] = i;//更新当前字符的下标 } if(len > s.length() - start)//针对没有重复字符的字符串 return len; else return s.length() - start; } }
相关文章推荐
- 电子常识
- 电子常识
- assert与if的区别
- Activiti源码分析
- 第二章 Python简介
- 2. Add Two Numbers
- java24为什么用抽象类
- 教你怎么半天搞定Docker
- MQ 概述
- Designing for Multi-Window
- 使用自定义模板为Myeclipse添加新建Filter的功能
- 笔试面试题8--内联函数和宏的区别
- Form表单的操作
- 将本地代码push到GitLab空仓库
- Tomcat安装实战
- VMware下ubuntu扩展磁盘空间
- 9、dwr的入门教程
- 1. Two Sum
- javaweb学习总结(四十五)——监听器(Listener)学习二
- Java8 随笔记录(三)