|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +/** |
| 5 | + * Given a string, find the length of the longest substring without repeating characters. |
| 6 | + * <p> |
| 7 | + * Examples: |
| 8 | + * Given "abcabcbb", the answer is "abc", which the length is 3. |
| 9 | + * Given "bbbbb", the answer is "b", with the length of 1. |
| 10 | + * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a |
| 11 | + * subsequence and not a substring. |
| 12 | + * Created by drfish on 13/05/2017. |
| 13 | + */ |
| 14 | +public class _003LongestSubStringWithoutRepeatingCharacters { |
| 15 | + public int lengthOfLongestSubstring(String s) { |
| 16 | + if (s == null) |
| 17 | + return 0; |
| 18 | + if (s.length() <= 1) |
| 19 | + return s.length(); |
| 20 | + Map<Character, Integer> map = new HashMap<>(); |
| 21 | + int start = -1; |
| 22 | + int result = 0; |
| 23 | + for (int i = 0; i < s.length(); i++) { |
| 24 | + if (map.containsKey(s.charAt(i))) { |
| 25 | + start = Math.max(start, map.get(s.charAt(i))); |
| 26 | + } |
| 27 | + map.put(s.charAt(i), i); |
| 28 | + result = Math.max(result, i - start); |
| 29 | + } |
| 30 | + return result; |
| 31 | + } |
| 32 | + |
| 33 | + public static void main(String[] args) { |
| 34 | + _003LongestSubStringWithoutRepeatingCharacters solution = new _003LongestSubStringWithoutRepeatingCharacters(); |
| 35 | + assert 3 == solution.lengthOfLongestSubstring("abcabcbb"); |
| 36 | + assert 1 == solution.lengthOfLongestSubstring("bbbbb"); |
| 37 | + assert 3 == solution.lengthOfLongestSubstring("pwwkew"); |
| 38 | + } |
| 39 | +} |
0 commit comments