Difficulty: Medium
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
Intuition
Method1: Refer to: 最长不含重复字符的子字符串
Method2: Traverse each char in the string and update the startIndex and the endIndex of the Substring.
Use array(size=256) to store lastIndex of current char.
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)
Space complexity : O(1)
What I've learned
1. size: ASCII——128; Extended ASCII——256
More:【目录】LeetCode Java实现