Leetcode3 最長不重複子串 C++,Java,Python

Leetcode3 最長不重複子串

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

博主Githubhttps://github.com/GDUT-Rp/LeetCode

題目:

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。

示例 1:

輸入: "abcabcbb"
輸出: 3 
解釋: 因爲無重複字符的最長子串是 "abc",所以其長度爲 3。

示例 2:

輸入: "bbbbb"
輸出: 1
解釋: 因爲無重複字符的最長子串是 "b",所以其長度爲 1。

示例 3:

輸入: "pwwkew"
輸出: 3
解釋: 因爲無重複字符的最長子串是 "wke",所以其長度爲 3。
     請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。

解題思路:

方法一:暴力法

直觀想法

逐個檢查所有的子字符串,看它是否不含有重複的字符。

算法

假設我們有一個函數 boolean allUnique(String substring) ,如果子字符串中的字符都是唯一的,它會返回 true,否則會返回 false。 我們可以遍歷給定字符串 s 的所有可能的子字符串並調用函數 allUnique。 如果事實證明返回值爲 true,那麼我們將會更新無重複字符子串的最大長度的答案。

現在讓我們填補缺少的部分:

爲了枚舉給定字符串的所有子字符串,我們需要枚舉它們開始和結束的索引。假設開始和結束的索引分別爲 ij。那麼我們有 0i<jn0 \leq i \lt j \leq n(這裏的結束索引 j 是按慣例排除的)。因此,使用 i 從 0 到 n1n - 1 以及 ji+1n 這兩個嵌套的循環,我們可以枚舉出 s 的所有子字符串。

要檢查一個字符串是否有重複字符,我們可以使用集合。我們遍歷字符串中的所有字符,並將它們逐個放入 set 中。在放置一個字符之前,我們檢查該集合是否已經包含它。如果包含,我們會返回 false。循環結束後,我們返回 true

C++

暴力法會超時,請直接參考滑動窗口算法

Java

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

Python

暴力法會超時,請直接參考滑動窗口算法

複雜度分析

時間複雜度:O(n3)O(n^3)

方法二:滑動窗口

直觀想法

暴力法非常簡單,但它太慢了。那麼我們該如何優化它呢?

在暴力法中,我們會反覆檢查一個子字符串是否含有有重複的字符,但這是沒有必要的。如果從索引 iij1j - 1 之間的子字符串 sijs_{ij} 已經被檢查爲沒有重複字符。我們只需要檢查 s[j]s[j] 對應的字符是否已經存在於子字符串 $s_{ij}中。

要檢查一個字符是否已經在子字符串中,我們可以檢查整個子字符串,這將產生一個複雜度爲 $O(n^2)的算法,但我們可以做得更好。

通過使用 HashSet 作爲滑動窗口,我們可以用 O(1)O(1) 的時間來完成對字符是否在當前的子字符串中的檢查。

滑動窗口是數組/字符串問題中常用的抽象概念。 窗口通常是在數組/字符串中由開始和結束索引定義的一系列元素的集合,即 [i,j)[i, j)(左閉,右開)。而滑動窗口是可以將兩個邊界向某一方向“滑動”的窗口。例如,我們將 [i,j)[i, j) 向右滑動 11 個元素,則它將變爲 [i+1,j+1)[i+1, j+1)(左閉,右開)。

回到我們的問題,我們使用 HashSet 將字符存儲在當前窗口 [i,j)[i, j)(最初 j=ij = i)中。 然後我們向右側滑動索引 jj,如果它不在 HashSet 中,我們會繼續滑動 jj。直到 s[j]s[j] 已經存在於 HashSet 中。此時,我們找到的沒有重複字符的最長子字符串將會以索引 ii 開頭。如果我們對所有的 ii 這樣做,就可以得到答案。

C++

//
// Created by Lenovo on 2019/1/1.
//

#ifndef LEETCODE_C_PLUSPLUS_LEETCODE3_H
#define LEETCODE_C_PLUSPLUS_LEETCODE3_H

#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <set>

using namespace std;


class Solution_LeetCode3 {
public:
    int lengthOfLongestSubstring(string s) {
        int ans = 0, i = 0, j = 0;
        set<char> charset;
        int length = s.length();
        while (i < length && j < length){
            if (!charset.count(s[j])){
                charset.insert(s[j++]);
                ans = max(ans, j - i);
            } else{
                charset.erase(s[i++]);
            }
        }
        return ans;
    }
};

#endif //LEETCODE_C_PLUSPLUS_LEETCODE3_H

Java

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

Python

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        滑動窗口方式解決,向右滑動
        時間複雜度: O(2n) = O(n)
        空間複雜度: O(min(m,n)) 取決於字符串 nn 的大小以及字符集/字母 mm 的大小
        :type s: str 輸出字符串
        :rtype: int 結果
        """
        length = len(s)
        charset = set()
        ans = 0
        i = 0
        j = 0
        while i < length and j < length:
            if not charset.__contains__(s[j]):
                charset.add(s[j])
                j = j + 1
                ans = max(ans, j - i)
            else:
                charset.remove(s[i])
                i = i + 1
        return ans

算法複雜度:

時間複雜度:O(2n)=O(n)O(2n) = O(n),在最糟糕的情況下,每個字符將被 iijj 訪問兩次。

空間複雜度:O(min(m,n))O(min(m, n)),與之前的方法相同。滑動窗口法需要 O(k)O(k) 的空間,其中 kk 表示 Set 的大小。而 Set 的大小取決於字符串 nn 的大小以及字符集 / 字母 mm 的大小。

方法三:優化的滑動窗口

直觀想法

上述的方法最多需要執行 2n2n 個步驟。事實上,它可以被進一步優化爲僅需要 nn 個步驟。我們可以定義字符到索引的映射,而不是使用集合來判斷一個字符是否存在。 當我們找到重複的字符時,我們可以立即跳過該窗口。

也就是說,如果 s[j]s[j][i,j)[i, j) 範圍內有與 jj 重複的字符,我們不需要逐漸增加 ii 。 我們可以直接跳過 [ij][i,j] 範圍內的所有元素,並將 ii 變爲 j+1j + 1

C++

//
// Created by Lenovo on 2019/1/1.
//

#ifndef LEETCODE_C_PLUSPLUS_LEETCODE3_H
#define LEETCODE_C_PLUSPLUS_LEETCODE3_H

#include <iostream>
#include <vector>
#include <cstdio>
#include <string>
#include <set>

using namespace std;


class Solution_LeetCode3 {
public:
    int improveByVector(string s){
        int length = s.length();
        int ans = 0, i = 0, j = 0;
        vector<int> index(128);
        for (; j < length ; j++) {
            i = max(index[s[j]], i);
            ans = max(ans, j - i + 1);
            index[s[j]] = j + 1;
        }
        return ans;
    }
};

#endif //LEETCODE_C_PLUSPLUS_LEETCODE3_H

Java

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

Python

class Solution:
    def improve_by_dict(self, s):
        """
        我們可以定義字符到索引的映射,而不是使用集合來判斷一個字符是否存在
        時間複雜度: O(2n) = O(n)
        :param s:
        :return:
        """
        length = len(s)
        ans = 0
        chardict = {}
        i, j = 0, 0
        while j < length:
            if chardict.__contains__(s[j]):
                i = max(i, chardict.get(s[j]))
            ans = max(ans, j - i + 1)
            chardict[s[j]] = j + 1
            j = j + 1
        return ans

算法複雜度:

時間複雜度:O(n)O(n),索引 jj 將會迭代 nn 次。

空間複雜度(HashMap):O(min(m,n))O(min(m, n)),與之前的方法相同。

空間複雜度(Table):O(m)O(m)mm 是字符集的大小。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章