LeetCodeOJ.Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝天天特价报名条件 编辑:程序博客网 时间:2024/05/17 04:02

试题请参见: https://leetcode.com/problems/longest-substring-without-repeating-characters/

题目概述

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"));    }}
0 0