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.
1 class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s.length() == 0) return 0; 4 char []s1 = s.toCharArray(); 5 int ans = 1; 6 Map<String, Integer> map = new HashMap<>(); 7 int num = 0; 8 for (int i = 0; i < s.length(); ++i) { 9 String tc = String.valueOf(s1[i]); 10 if (map.containsKey(tc)) { 11 int temp = i - map.get(tc); 12 if (temp <= num) { 13 num = temp; 14 } else { 15 num++; 16 } 17 18 } else { 19 num++; 20 } 21 map.put(tc, i); 22 23 24 if (num > ans) { 25 ans = num; 26 } 27 } 28 return ans; 29 } 30 }