LeetCode - 3 -Longest Substring Without Repeating Characters

題目描述

Given a string, find the length of the longest substring without repeating characters.

例子

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

Java實現_1

import java.util.HashSet;

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> charSet = new HashSet<>();
        int ans = 0;
        int i = 0;
        int j = 0;
        while (i < n && j < n){
            if (!charSet.contains(s.charAt(j))){
                charSet.add(s.charAt(j++));
                //j++,先後延一位,因此ans計算正常
                ans = Math.max(ans, j - i);
            }else {
                charSet.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

Java實現_2

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        //使用Map存儲 字符和字符位置
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0, j = 0; j < n; j++){
            //若map中存在Key,移動i到Max(map中的key位置, i)
            if (map.containsKey(s.charAt(j))){
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章