leetcode(3):Longest Substring Wi

作者: 李子悟 | 来源:发表于2019-03-28 20:17 被阅读16次

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
Explanation: The answer is "b", with the length of 1.

题意简单明了大致就是计算一个字符串的无重复字符 的最长子字符串长度(子字符串即为连续的子字符串)

最容易想到的实现就是两层for循环遍历,找到最大子字符串,下面是笔者第一版的实现

public int lengthOfLongestSubstring(String s) {
        int maxlength = 0;
        for (int i = 0; i < s.length(); i++) {
            Set<Character> numbers = new HashSet<>();
            int times = 0;
            for (int j = i; j < s.length(); j++) {
                numbers.add(s.charAt(j));
                times++;
                int size = numbers.size();
                if (size < times || size >= s.length() - i) {
                    if (maxlength < size) {
                        maxlength = size;
                    }
                    break;
                }
            }
        }
        return maxlength;
    }

提交后发现:
Runtime: 54 ms, faster than 22.41% of Java online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 38.5 MB, less than 31.95% of Java online submissions for Longest Substring Without Repeating Characters.

这一版的算法复杂度O(n^2),但是结果被leetcode大神完虐。这让笔者意识到这道题应该有线性解或者对数解。受限于目前算法的掌握程度还没有学习到字符串算法哪里,但是又不想去参考答案,所以这一版先到此告一段落。等笔者学习完字符串的各种 算法后再回过头来重新实现,所以标题为(defect) 。

相关文章

网友评论

    本文标题:leetcode(3):Longest Substring Wi

    本文链接:https://www.haomeiwen.com/subject/nsocbqtx.html