3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

SOlution 1: Brute force
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int ln = s.length();
        int res = 0;
        for(int i = 0; i < ln; i++){
            for(int j = i+1; j <=ln; j++){
                if(isUnique(s, i, j))res = Math.max(res, j-i);
            }
        }
        return res;
    }
    public  boolean isUnique(String st, int start, int end){
            ArrayList<Character> list = new ArrayList<Character>();
            for(int i = start; i < end; i++){
                Character ch = st.charAt(i);
                if(list.contains(ch)) return false;
                list.add(ch);
            }
            return true;
        }
}

  主程序重用两层for loop保证每个组合可以被检查,用什么检查呢?用isUnique method。然后submit,Time limit Exceeded。。

SOlution2:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        int[] index = new int[128]; // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            i = Math.max(index[s.charAt(j)], i);
            ans = Math.max(ans, j - i + 1);
            index[s.charAt(j)] = j + 1;
        }
        return ans;
    }
}

 上面是贪心法,一刷并没有看懂。思路是这样的:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] dict = new int[256];
        Arrays.fill(dict, -1);    
        int max_len = 0;
        for(int i = 0, start = 0; i < s.length(); i++){   
           start = Math.max(start, dict[s.charAt(i)] + 1);
           max_len = Math.max(max_len, i - start + 1);//每次最大长度都更新
           dict[s.charAt(i)] = i;
        }
        return max_len;
    }
}

屌啊。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10204173.html