Longest Substring Without Repeating Characters

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

Examples:

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.

 

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         int maxSubstringLength = 0;
 4         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 5         int left = 0, n = s.length();
 6         for (int i = 0; i < n; i++) {
 7             Character key = s.charAt(i);
 8             if (map.containsKey(key))
 9                 left = Math.max(left, map.get(key) + 1);
10             map.put(key, i);
11             maxSubstringLength = Math.max(maxSubstringLength, i - left + 1);
12         }
13         return maxSubstringLength;
14     }
15 }

 

posted @ 2017-04-20 12:51  amazingzoe  阅读(103)  评论(0编辑  收藏  举报