[Leetcode] Longest Substring Without Repeating Characters

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.

Solution1:

暴力解:;

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s == null || s.length() == 0)
 4             return 0;
 5         if (s.length() == 1)
 6             return 1;
 7         HashMap<String, Integer> hm = new HashMap<String, Integer>();
 8         int result = 0;
 9         int start = 0;
10         int end = 0;
11         int N = s.length();
12 
13         while (start != N) {
14             if (!hm.containsKey(s.charAt(start) + ""))
15                 hm.put(s.charAt(start) + "", 1);
16             for (end = start + 1; end < N; ++end) {
17                 if (hm.containsKey(s.charAt(end) + "")) {
18                     if ((end - start) > result) {
19                         result = end - start;
20                     }
21                     break;
22                 } else {
23                     hm.put(s.charAt(end) + "", 1);
24                 }
25             }
26             start++;
27         }
28         return result;
29     }
30 }

Solution2:

http://blog.csdn.net/likecool21/article/details/10858799

 1 package POJ;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.HashMap;
 6 import java.util.LinkedList;
 7 import java.util.List;
 8 
 9 public class Solution {
10     public static void main(String[] args) {
11         Solution so = new Solution();
12         System.out.println(so.lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"));
13     }
14 
15     public int lengthOfLongestSubstring(String s) {
16         if (s == null || s.length() == 0)
17             return 0;
18         if (s.length() == 1)
19             return 1;
20         int[] hash = new int[256];
21         Arrays.fill(hash, -1);
22         int start = 0;
23         int end = start + 1;
24         int result = 1;
25         hash[s.charAt(0)] = 0;
26         while(end<s.length()){
27             if(hash[s.charAt(end)]>=start){
28                 start=hash[s.charAt(end)]+1;
29             }
30             result=Math.max(result, end-start+1);
31             hash[s.charAt(end)]=end;
32             end++;
33         }
34         return result;
35     }
36 }
原文地址:https://www.cnblogs.com/Phoebe815/p/4020603.html