Longest Substring Without Repeating Characters

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.

开始想用穷举法,将所有的子串都遍历出来,结果超时了。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if(s.length() == 0){
 4             return 0;
 5         }
 6         if(s.length() == 1)
 7             return 1;
 8         int result = 1;
 9         for(int i = 0; i < s.length() - result; i++){
10             int j = i + 1;
11             for(; j < s.length(); j++){
12                 String sub = s.substring(i, j);
13                 if(-1 == sub.indexOf(s.charAt(j)))
14                 {
15                     if(sub.length() + 1 > result)
16                         result = sub.length() + 1;
17                     continue;
18                 }
19                 break;
20             }
21         }
22         
23         return result;
24     }
25 }

参考了别人的,只遍历字符串一遍,用hash表记录s.charAt(i)的位置。不断更新result,有点贪心算法的感觉,每次记录当前字符串的起始位置

参考的连接我懒得找就不贴出来了

import java.util.Hashtable;

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0){
            return 0;
        }
        if(s.length() == 1)
            return 1;
        int result = 0;                                        //最后返回的结果
        int index = -1;                                        //当前子串开始位置的前一个位置
        Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();    //s[i]出现的位置
        
        for(int i = 0; i < s.length(); i++){
            Integer position = map.get(s.charAt(i));
            if(null != position && position > index)
                index = position;
            if(i - index > result)
                result = i - index;
            map.put(s.charAt(i), i);
        }
        
        return result;
    }
}
原文地址:https://www.cnblogs.com/luckygxf/p/4187456.html