LeetCode - 3. Longest Substring Without Repeating Characters

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

Example 1:spa

Input: "abcabcbb"
Output: 3 Explanation: The answer is , with the length of 3. "abc"

Example 2:指針

Input: "bbbbb"
Output: 1 Explanation: The answer is , with the length of 1. "b"

Example 3:code

Input: "pwwkew"
Output: 3 Explanation: The answer is , with the length of 3. Note that the answer must be a substring,  is a subsequence and not a substring.

求最長不含重複字符字串,雙指針,求最大兩相同字符的距離便可。時間複雜度O(n),空間複雜度O(n)。題目沒說必定全是字母因此不能使用256長度數組替代map,若是能夠時間複雜度是O(1)。"wke""pwke"
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() <= 0)
            return 0;
        Map<Character, Integer> map = new HashMap<>();
        int ret = 0;
        for (int i=0,j=0; i<s.length(); i++) {
            char ch = s.charAt(i);
            if (map.containsKey(ch)) {
                j = Math.max(j, map.get(ch) + 1);
            }
            ret = Math.max(ret, i-j+1);
            map.put(ch, i);
        }
        return ret;
    }
}
相關文章
相關標籤/搜索