算法天天練1:計算最長子串


題目來源: https://leetcode.com/problems/longest-substring-without-repeating-characters/solution/
問題描述: 計算一個字符串的最長子串的長度,子串不允許包含重復字符。
舉例說明:

輸入字符串 返回結果 解釋
abcabcbb 3 最長子串是abc
bbbbb 1 最長子串是b
pwwkew 3 最長子串是wke

解決方案

  1. 雙重遍歷獲得所有子串,再檢查子串是否包含重復字符,時間復雜度Ο(n^2)
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;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM