leetcode-3-longest-substring-without-repeating-characters

Description

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

Example 1:

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

Example 2:

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

Example 3:

1
2
3
4
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.

####

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.HashMap;
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0) return 0;
//新建一个map进行存储char
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
int leftBound = 0;
int max = 0;
for(int i=0; i<s.length();i++){
char c = s.charAt(i);
//窗口左边可能为下一个char,或者不变
leftBound = Math.max(leftBound,(map.containsKey(c))? map.get(c)+1:0);
max = Math.max(max, i-leftBound+1);//当前窗口长度
map.put(c,i);
}
return max;

}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×