问题:

Given a string, find the length of the longest substring without repeating characters.
Example:
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.

官方难度:

Medium

翻译:

给定一个字符串,找出最长子串的长度,且在子串中无重复字符。

例子:

字符串1:“abcabcbb”,长度为3。

字符串2:“bbbbb”,长度为1。

字符串3:“pwwkew”,长度为3。

  1. 用String.toCharArray()方法,将给定字符串拆成单个字符数组形式,开始遍历。
  2. 记录最长子串长度maxLength,初始值赋为0;记录当前子串列表list。
  3. 如果当前字符,不在当前子串内,将当前字符加入子串。
  4. 如果当前字符,存在当前子串内,先根据当前子串长度list.size()和maxLength的值,取其中大值,更新maxLength。然后找到上一个重复字符的index,删除子串内index位置之前的所有字符(包括index位置的字符)。最后,将当前字符加入子串。
  5. 在结束循环之后,再次检查当前子串长度list.size()和maxLength的值,取大值更新maxLength。因为可能出现最长子串是包含最后一个字符的子串。
  6. 注意检查入参。

解题代码:

 public static int lengthOfLongestSubstring(String s) {
if (s == null) {
throw new IllegalArgumentException("Input error");
}
char[] charArray = s.toCharArray();
int maxLength = 0;
List<Character> list = new ArrayList<>();
for (int i = 0; i < charArray.length; i++) {
Character c = charArray[i];
// 判断当前字符是否重复
if (list.contains(c)) {
// 更新最大长度
maxLength = list.size() > maxLength ? list.size() : maxLength;
// 删除重复之前的字符
int lastIndex = list.indexOf(c);
// lastIndex+1 代表删除次数
while (lastIndex + 1 > 0) {
list.remove(0);
lastIndex--;
} }
// 当前字符是一定要加的
list.add(c);
}
// 特殊情况考虑:最长字符串在原字符串尾部
maxLength = list.size() > maxLength ? list.size() : maxLength;
return maxLength;
}

lengthOfLongestSubstring

相关链接:

https://leetcode.com/problems/longest-substring-without-repeating-characters/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/medium/Q003.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

最新文章

  1. UML类图简单介绍
  2. MySQL中的两种临时表
  3. IOS 本地通知推送消息
  4. SQL错误级别 状态 怎么定义
  5. 与众不同 windows phone (43) - 8.0 相机和照片: 镜头的可扩展性, 图片的可扩展性, 图片的自动上传扩展
  6. 设计模式学习起点 UML类图笔记
  7. angular Creating a Directive that Adds Event Listeners
  8. LZMA demo挑选使用备忘
  9. Pythono 实现 Permutation
  10. Nmap 源代码学习四 软件简单使用
  11. 影响pogo pin连接器使用寿命的因素
  12. sublimtest3文件名乱码问题及解决方案
  13. seg格式文件的分析
  14. TRIZ系列-创新原理-32-改变颜色原理
  15. 三、Python-列表
  16. LINUX用户、组、权限管理和归档压缩、时间、Ping
  17. nullptr/NULL
  18. Cordova Error: cmd: Command failed with exit code ENOENT
  19. 36.scrapy框架采集全球玻璃网数据
  20. System.Data.SQLite安装的相关问题

热门文章

  1. file_get_contents()获取https出现这个错误Unable to find the wrapper “https” – did
  2. winform C#获得Mac地址,IP地址,子网掩码,默认网关
  3. SQL查询 - 表连接
  4. 在Unity3D的网络游戏中实现资源动态加载
  5. makeJar
  6. 天朝专用- 配置pypi镜像
  7. 九度OJ 1502 最大值最小化(JAVA)
  8. C#基础总结之七面向对象知识点总结1
  9. Linux 时钟与计时器
  10. 实例演示 kino.razor (前端 Javascript 模板工具,Razor 风格)的使用