【LeetCode】3. Longest Substring Without Repeating Characters

Difficulty: Medium

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/longest-substring-without-repeating-characters/java

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

Example 1:ui

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

Example 2:url

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

Example 3:spa

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."wke""pwke"

Intuition

Method1: Refer to: 最長不含重複字符的子字符串code

 Method2: Traverse each char in the string and update the startIndex and the endIndex of the Substring.htm

Use array(size=256) to store lastIndex of current char.blog

Solution

    public int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()<=0)
            return 0;
        int[] lastIndex = new int[256];
        for(int i=0;i<256;i++)
            lastIndex[i]=-1;
        int maxLen=0;
        int startIndex=0;
        for(int endIndex=0;endIndex<s.length();endIndex++){
            if(lastIndex[s.charAt(endIndex)]>=startIndex)
                startIndex=lastIndex[s.charAt(endIndex)]+1;
            maxLen=Math.max(endIndex-startIndex+1,maxLen);
            lastIndex[s.charAt(endIndex)]=endIndex;
        }
        return maxLen;
    }

  

Complexity

Time complexity : O(n)ip

Space complexity :  O(1)

What I've learned

1. size: ASCII——128;  Extended ASCII——256

 

 More:【目錄】LeetCode Java實現

相關文章
相關標籤/搜索