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 }

 

转载于:https://www.cnblogs.com/Jellylovecode/p/Longest-Substring-Without-Repeating-Characters.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值