算法天天练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;
    }
}
posted @ 2019-10-08 10:49  编码专家  阅读(1364)  评论(0编辑  收藏  举报