Longest Substring Without Repeating Characters
2015-08-11 15:01
316 查看
问题描述
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.
解决思路
双指针 + HashSet
前后两个指针,开始时均指向第一个元素,将第一个元素加入HashSet中。
然后移动后指针,只要set中不包含指向元素则移动后指针,不断记录两个指针间的最大长度差(即为不重复字符的字符串)。
时间复杂度和空间复杂度均为O(n).
程序
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.
解决思路
双指针 + HashSet
前后两个指针,开始时均指向第一个元素,将第一个元素加入HashSet中。
然后移动后指针,只要set中不包含指向元素则移动后指针,不断记录两个指针间的最大长度差(即为不重复字符的字符串)。
时间复杂度和空间复杂度均为O(n).
程序
public class Solution { public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) { return 0; } int len = s.length(); int max = 1; HashSet<Character> set = new HashSet<>(); int low = 0, high = 0; while (high < len) { char c = s.charAt(high); if (!set.contains(c)) { set.add(c); ++high; max = Math.max(max, high - low); continue; } char t = s.charAt(low); set.remove(t); ++low; } return max; } }
相关文章推荐
- [动态规划]最大连续子序列和
- iOS开发之使用Storyboard预览UI在不同屏幕上的运行效果
- JS+CSS实现美化的下拉列表框效果
- Python 加密 md5
- 互联网电商大数据环境 ——大数飓数据分析实践培训精华笔记(三)——数据仓库理论
- java调用http传json数据或字符串
- 172 Factorial Trailing Zeroes
- 最好最易懂的Git教学——分享“好麻烦部落格”Git教学(3)
- 使用org.w3c.dom.Element的setTextContent()、getTextContent()方法时出现编译错误
- 前端组件化开发实践
- python---urllib模块
- iOS学习之block总结及block内存管理(必看)
- 【技术】jquery里.length和.size()区别
- 左神牛课网讲座第二发 算法讲解
- ASP.NET MVC3模板页的使用(2)
- Linux基础学习笔记-第二课:磁盘相关
- jvm 内存分析
- 怎样运行地理处理工具 Geoprocessing & Geoprocessor & IGPProcess
- linux中fork()函数详解(原创!!实例讲解)
- dexposed框架Android在线热修复