题目描述
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;
}
}