More:【目錄】LeetCode Java實現html
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"
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
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; }
Time complexity : O(n)ip
Space complexity : O(1)
1. size: ASCII——128; Extended ASCII——256
More:【目錄】LeetCode Java實現