【算法】【字符串】无重复字符的最长子串

1  题目

给定一个字符串 s ,请你找出其中不含有重复字符的 最长连续子字符串 的长度。

示例 1:

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子字符串是 "abc",所以其长度为 3

示例 2:

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子字符串是 "b",所以其长度为 1

示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

示例 4:

输入: s = ""
输出: 0

提示:

  • 0 <= s.length <= 5 * 104
  • s 由英文字母、数字、符号和空格组成

2  解答

绞尽脑汁,咋我老绕自己呢,下边这个能通过,我明天抽空再想想,看看还有什么思路还有哪些能优化的:

复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int res = 0;
        // 参数边界校验
        if (s == null || s.length() == 0) {
            return res;
        }

        // 当发现重复的就记录当前最长的
        int currentStart = 0;
        String maxStr = "";
        String currentStr = "";
        for (int i = 1; i < s.length(); i++) {
            String subChar = s.charAt(i) + "";
            currentStr = s.substring(currentStart, i + 1);
            // 前面的串不包含当前字符,那就继续向后
            int index = currentStr.indexOf(subChar);
            if (index == currentStr.length() - 1) {
                continue;
            }
            // 包含当前的字符了
            if (currentStr.length() - 1 >= maxStr.length()) {
                maxStr = s.substring(currentStart, i);
            }
            currentStart += (index + 1);
            currentStr = "";
        }
        if (maxStr.length() == 0) {
            return s.length();
        }
        return Math.max(maxStr.length(), currentStr.length());
    }
}
复制代码

来了,来了,一次遍历清晰的逻辑:

复制代码
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        if (s == null || s.length() <= 0) {
            return max;
        }
        StringBuilder subStr = new StringBuilder(s.charAt(0) + "");
        for (int i = 1; i < s.length(); i++) {
            String current = s.charAt(i) + "";
            int index = subStr.indexOf(current);
            // 如果不包含,则继续
            if (index < 0) {
                subStr.append(current);
                continue;
            }
            // 遇到重复的了 算是一种结果
            max = Math.max(max, subStr.length());
            // 删掉那个重复的
            subStr = new StringBuilder(subStr.substring(index + 1));
            subStr.append(current);
        }
        max = Math.max(max, subStr.length());
        return max;
    }
}
复制代码

加油。

posted @   酷酷-  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-02-26 【Mybatis】【配置文件解析】【四】Mybatis源码解析-mappers的解析二(resultMap)
2023-02-26 【Mybatis】【配置文件解析】【四】Mybatis源码解析-mappers的解析一(cache、cache-ref)
2023-02-26 【Mybatis】【配置文件解析】【三】Mybatis源码解析-typeHandler、objectWrapperFactory
2023-02-26 【Mybatis】【基础设施】【四】Mybatis源码解析-ResolverUtil解析工具
2023-02-26 【Mybatis】【基础设施】【三】Mybatis源码解析-VFS虚拟文件系统
点击右上角即可分享
微信分享提示