1. 程式人生 > >leecode_2

leecode_2

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

這個題目是為了獲得字串中沒有重複子字串的長度。

第一種方法,暴力搜尋。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int ans = 0;
        for (int i = 0; i < n; i++)
            //注意這裡j可以等於n,當等於n時,下面的allUnique方法裡面的i的範圍就必須為i<end,不能等於,不然就越界了。
            for (int j = i + 1; j <= n; j++)
                if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
        return ans;
    }
    public boolean allUnique(String s, int start, int end) {
           //將從start到end-1的字元放入到set中,set中是不能存在相同的字元的。
        Set<Character> set = new HashSet<>();
        for (int i = start; i < end; i++) {
            Character ch = s.charAt(i);
            if (set.contains(ch)) return false;
            set.add(ch);
        }
        return true;
    }
}

第二種方法。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0, i = 0, j = 0;
        while (i < n && j < n) {
            // try to extend the range [i, j]
            //當set中不存在要新增的當前字元時,就將字元放入到set中,並計算新增進set中的字元長度
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
           //當set中存在要新增的字元時,就將set中要新增的字元和其之前的字元全都移除。
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}