大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Java技巧 > LeetCode: Longest Substring Wi

LeetCode: Longest Substring Wi

关键词:LongestLeetCodeSubstringCha  阅读(1185) 赞(10)

[摘要]本文是对LeetCode: Longest Substring Without Repeating Characters的讲解,对学习Java编程技术有所帮助,与大家分享。
 /**
  * 
  */
 package solution;
 
 import java.util.HashMap;
 
 /**
  * @author whh
  * 
  *         Given a string, find the length of the longest substring without
  *         repeating characters. For example, the longest substring without
  *         repeating letters for "abcabcbb" is "abc", which the length is 3. For
  *         "bbbbb" the longest substring is "b", with the length of 1.
  */
 public class LongestSubstringWithoutRepeatingCharacters {
 
     /**
      * @param args
      */
     public static void main(String[] args) {
         String s1 = "abcabcbb", s2 = "aaa", s3 = "abcdefghijklmnopqrstuvwxyz";
         String s4 = "wlrbbmqbhcdarzowkk";
         String s5 = "qopubjguxhxdipfzwswybgfylqvjzhar";
         System.out.println(lengthOfLongestSubstring(s1));
         System.out.println(lengthOfLongestSubstring(s2));
         System.out.println(lengthOfLongestSubstring(s3));
         System.out.println(lengthOfLongestSubstring(s4));
         System.out.println(lengthOfLongestSubstring(s5));
 
     }
 
     /**
      * @param s
      * @return
      */
     public static int lengthOfLongestSubstring(String s) {
 
         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
 
         int begin = 0, maxLength = 0;
         for (int end = 0; end < s.length(); end++) {
             Character character = s.charAt(end);
             if (!map.containsKey(character)) {
                 map.put(character, 1);
             } else {
                 map.put(character, map.get(character) + 1);
             }
 
             if (map.get(character) == 2) {
                 while (map.get(s.charAt(begin)) <= 1) {
                     map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
                     begin++;
                 }
                 map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1);
                 begin++;
             }
             if ((end - begin + 1) >= maxLength) {
                 maxLength = end - begin + 1;
             }
         }
 
         return maxLength;
     }
 }


相关评论