Longest Substring Without Repeating Characters
来源:互联网 发布:单片机无线收发模块 编辑:程序博客网 时间:2024/06/13 22:14
给定跟一个字符串,找出一个不含重复的最长子串
分析:
显然用map很简单,但是会超时;
“最后,我们介绍一种线性的算法,也是这类题目最常见的方法。基本思路是维护一个窗口,每次关注窗口中的字符串,在每次判断中,左窗口和右窗口选择其一向前移动。同样是维护一个HashSet, 正常情况下移动右窗口,如果没有出现重复则继续移动右窗口,如果发现重复字符,则说明当前窗口中的串已经不满足要求,继续移动右窗口不可能得到更好的结果,此时移动左窗口,直到不再有重复字符为止,中间跳过的这些串中不会有更好的结果,因为他们不是重复就是更短。因为左窗口和右窗口都只向前,所以两个窗口都对每个元素访问不超过一遍,因此时间复杂度为O(2*n)=O(n),是线性算法。空间复杂度为HashSet的size,也是O(n). ”
设置两个指针,left和right,分别遍历一边字符串;
当right遍历过的字符,set中不存在时,则加入set,right往前一位;当该字符set中已经存在,则判断左右窗口的大小是否大于当前最大窗口的大小max,若大于,则重新给max赋值;然后重复判断left的字符是否与right的相等,若不相等,说明left到right窗口中含有重复元素,此窗口不能使用,需要把left的元素从set中删除,left往前一步,知道left元素等于right元素,说明正是left元素造成了使“该字符set中已经存在”的现象,可以跳出来,然后left++;开始下一段不重复的子串的旅程;
参考代码如下:
http://blog.csdn.net/linhuanmars/article/details/19949159
public class Solution { public int lengthOfLongestSubstring(String s) { if(s==null || s.length()==0) return 0; HashSet<Character> set = new HashSet<Character>(); int max = 0; int walker = 0; int runner = 0; while(runner<s.length()) { if(set.contains(s.charAt(runner))) { if(max<runner-walker) { max = runner-walker; } while(s.charAt(walker)!=s.charAt(runner)) { set.remove(s.charAt(walker)); walker++; } walker++; } else { set.add(s.charAt(runner)); } runner++; } max = Math.max(max,runner-walker); return max;}}
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- 一些经常用到的linux命令
- 打开CMDLINE中的 ” earlyprink “ 参数
- 【Ubuntu下配置shadowsocks-libv客户端】
- 局部对象
- Windows下图文详解PHP三种运行方式(php_mod、cgi、fastcgi)
- Longest Substring Without Repeating Characters
- 对链表的操作为什么要使用二级指针
- iOS及Mac开源项目和学习资料【超级全面】
- Real-time human pose recognition in parts from single depth images 中文翻译【译】【中译】微软kinect中用的算法
- java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
- mq异步发送
- java组合、继承
- vmware虚拟机和win7主机共享文件(简单、快捷)
- Java文件下载