LeetCodeOJ.Longest Substring Without Repeating Characters
2015-10-08 14:03
447 查看
试题请参见: https://leetcode.com/problems/longest-substring-without-repeating-characters/
简单地说, 解决这一类问题的基本思路是: 快慢指针. 正常情况下, 快指针一直向右移动, 并将所读到的字符放入HashSet中. 直到快指针所读到的字符在HashSet中已经出现, 记录此时快慢指针的差值并更新最大子串的长度. 同时, 在HashSet中删除慢指针所对应的字符, 直到快指针可以继续向右侧移动.
题目概述
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.解题思路
The idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or not, if not, great, add it to the hash set, move j forward and update the max length, otherwise, delete from the head by using a slow pointer i until we can put character j to the hash set.简单地说, 解决这一类问题的基本思路是: 快慢指针. 正常情况下, 快指针一直向右移动, 并将所读到的字符放入HashSet中. 直到快指针所读到的字符在HashSet中已经出现, 记录此时快慢指针的差值并更新最大子串的长度. 同时, 在HashSet中删除慢指针所对应的字符, 直到快指针可以继续向右侧移动.
源代码
import java.util.HashSet; import java.util.Set; public class Solution { public int lengthOfLongestSubstring(String s) { int walker = 0, runner = 0, max = 0; Set<Character> set = new HashSet<Character>(); while ( runner < s.length() ) { if ( !set.contains(s.charAt(runner)) ) { set.add(s.charAt(runner ++)); max = Math.max(max, set.size()); } else { while ( set.contains(s.charAt(runner)) ) { set.remove(s.charAt(walker ++)); } } } return max; } public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.lengthOfLongestSubstring("bbbbb")); } }
相关文章推荐
- 最长递增子序列
- 数学问题和狼追兔问题
- eclipse下修改tomcat的URIEncoding为UTF-8
- 计算1/1-1/2+1/3-1/4......+1/99-1/100的值
- 详细透彻的分析DM9000网卡驱动程序(1)
- 分享txt转换pdf格式具体转换方法
- sh脚本语法_基础
- 在一个Activity 里面去关闭另一个Activity或者多个Acitivity
- 各种RAID的理解
- 20个非常有用的Java程序片段
- Java 理论与实践: 变还是不变?
- 惠普公司将拆成两家公司
- GET 和 平 POST 的区别详解
- Swift2.1 语法指南——基本运算符
- 查看服务器CPU信息工具脚本
- 【Scala学习笔记】4. For、Function、Lazy
- ocp-199
- ocp-198
- Sublime2 中文乱码问题
- 通过分析 JDK 源代码研究 Hash 存储机制