LeetCodeOJ.Longest Substring Without Repeating Characters

試題請參見: 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"));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章