【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<Character, Integer> 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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值