1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import java.util.HashMap; import java.util.Map;
public class Solution { public static int lengthOfLongestSubstring(String s) { int maxLength = 0; Map<Character, Integer> window = new HashMap(); for (int i = 0, j = 0; j < s.length(); j++) { if (window.containsKey(s.charAt(j))) { i = Math.max(window.get(s.charAt(j)) + 1, i); } window.put(s.charAt(j), j); int length = j - i + 1; maxLength = Math.max(maxLength, length); } return maxLength; }
public static void main(String[] args) { System.out.println("lengthOfLongestSubstring(\"abba\") = " + lengthOfLongestSubstring("abba")); } }
|