栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

题目

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

  • s 由英文字母、数字、符号和空格组成
题解 方法1

参考热评题解:

  1. 创建数组用于记录字符上一次出现的位置
  2. beg变量用于记录无重复子串的开始位置,并保证窗口开端不会左移
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] last = new int[128];  //记录字符上一次出现的位置
        for(int i = 0; i < 128; ++i) {
            last[i] = -1;
        }
        int len = s.length();
        int beg = 0;
        int res = 0;
        for(int i = 0; i < len; ++i) {
            int ch = s.charAt(i);
            beg = Math.max(beg, last[ch] + 1);  //"abba"
            res = Math.max(res, i - beg + 1);
            last[ch] = i;
        }
        return res;
    }
}

同理,利用HashMap记录字符出现的位置

class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap hashMap = new HashMap<>();
        int res = 0, beg = 0;
        for(int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if(hashMap.containsKey(ch)) {
                beg = Math.max(beg, hashMap.get(ch) + 1);
            }
            res = Math.max(res, i - beg + 1);
            hashMap.put(ch, i);
        }
        return res;
    }
}
方法2

遍历字符串s,利用StringBuilder创建无重复字符的子串,并获取最长子串的长度

class Solution {
    public int lengthOfLongestSubstring(String s) {
        StringBuilder sb = new StringBuilder();
        int res = 0;
        for(int i = 0; i < s.length(); ++i) {
            String str = String.valueOf(s.charAt(i));
            int idx = sb.indexOf(str);  //str在sb中第一次出现位置的索引
            if(idx >= 0) {
                sb.delete(0, idx + 1);  //删除,左闭右开
            }
            sb.append(s.charAt(i));
            res = Math.max(sb.length(), res);
        }
        return res;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号