找出字符串中不重复的最大长度的子串长度

本文介绍了一种用于寻找字符串中最长无重复字符子串的算法实现,通过使用HashSet数据结构来跟踪已出现的字符,确保子串内字符的唯一性。文章提供了完整的Java代码示例,展示了如何在给定字符串中找到最长的不重复字符子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意子串的意思是字符串中的某一个连续片段
而下边这个代码找出的最大长度的子序列,并不是子串。

public class MainString {
    public static String lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();//set集合元素无序,不重复
        for(int i=0;i<n;i++ ) {
            if(!set.contains(s.charAt(i))){
                set.add(s.charAt(i));
            }
        }
        return set.toString();
    }

    public static void main(String[] args) {
        String s="abczaada";
        System.out.println(lengthOfLongestSubstring(s));
    }
}

找出字符串中不重复的最大长度的子串长度

public class MainString {
    public static int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();//set集合元素无序,不重复
        int i=0,ans=0,j=0;
        while(i<n&&j<n){
            if(set.contains(s.charAt(j))){
                set.remove(s.charAt(i++));  //如果有重复元素,从第一个开始删除之前添加的元素,直到删除与新添加的钙元素重复的元素为止。
            }else{
                set.add(s.charAt(j++));
                ans=Math.max(ans,j-i);//删除了i个元素,因此还剩j-i个元素。
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        String s="abczaada";
        System.out.println(lengthOfLongestSubstring(s));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值