LeetCode: Longest Substring Without Repeating Characters

 1 /**
 2  * 
 3  */
 4 package solution;
 5 
 6 import java.util.HashMap;
 7 
 8 /**
 9  * @author whh
10  * 
11  *         Given a string, find the length of the longest substring without
12  *         repeating characters. For example, the longest substring without
13  *         repeating letters for "abcabcbb" is "abc", which the length is 3. For
14  *         "bbbbb" the longest substring is "b", with the length of 1.
15  */
16 public class LongestSubstringWithoutRepeatingCharacters {
17 
18     /**
19      * @param args
20      */
21     public static void main(String[] args) {
22         String s1 = "abcabcbb", s2 = "aaa", s3 = "abcdefghijklmnopqrstuvwxyz";
23         String s4 = "wlrbbmqbhcdarzowkk";
24         String s5 = "qopubjguxhxdipfzwswybgfylqvjzhar";
25         System.out.println(lengthOfLongestSubstring(s1));
26         System.out.println(lengthOfLongestSubstring(s2));
27         System.out.println(lengthOfLongestSubstring(s3));
28         System.out.println(lengthOfLongestSubstring(s4));
29         System.out.println(lengthOfLongestSubstring(s5));
30 
31     }
32 
33     /**
34      * @param s
35      * @return
36      */
37     public static int lengthOfLongestSubstring(String s) {
38 
39         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
40 
41         int begin = 0, maxLength = 0;
42         for (int end = 0; end < s.length(); end++) {
43             Character character = s.charAt(end);
44             if (!map.containsKey(character)) {
45                 map.put(character, 1);
46             } else {
47                 map.put(character, map.get(character) + 1);
48             }
49 
50             if (map.get(character) == 2) {
51                 while (map.get(s.charAt(begin)) <= 1) {
52                     map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
53                     begin++;
54                 }
55                 map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
56                 begin++;
57             }
58             if ((end - begin + 1) >= maxLength) {
59                 maxLength = end - begin + 1;
60             }
61         }
62 
63         return maxLength;
64     }
65 }

 

posted @ 2014-05-23 19:34  Jelly_  阅读(326)  评论(0编辑  收藏  举报