1. 程式人生 > >給定一個字符串,找到最長子串的長度,而不重復字符。

給定一個字符串,找到最長子串的長度,而不重復字符。

class cnblogs end style [] 檢測 sub 子串 必須

描述:

給定一個字符串,找到最長子串的長度,而不重復字符。

例子:

給定"abcabcbb"的答案是"abc",長度是3。

給定"bbbbb"的答案是"b",長度為1。

給定"pwwkew"的答案是"wke",長度為3.請註意,答案必須是子字符串"pwke"序列,而不是子字符串。

LeetCode給出的方法:

1、假設有一個函數allUnique(),能檢測某字符串的子串中的所有字符都是唯一的(無重復字符),那麽就可以實現題意描述:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        
int n = s.length(); int ans = 0; for (int i = 0; i < n; i++) 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) { 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; } }

2、滑動窗口思想:如果確定子串s[i,j](假設表示字符串的第i個字符到第j-1個字符表示的子串),那麽只需要比較s[j]是否與子串s[i,j]重復即可

若重復:記錄此時滑動窗口大小,並與最大滑動窗口比較,賦值。然後滑動窗口大小重定義為1,頭位置不變,並右移一個單位。

若不重復:滑動窗口頭不變,結尾+1,整個窗口加大1個單位。繼續比較下一個。

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]
            if (!set.contains(s.charAt(j))){
                set.add(s.charAt(j++));
                ans = Math.max(ans, j - i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

3、使用HashMap

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

4、

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;
    }
}

給定一個字符串,找到最長子串的長度,而不重復字符。