算法-最长无重复子串

该博客主要探讨了如何在Java中找到一个字符串中最长的无重复字符的子串。提供了两种不同的实现方法,一种使用HashSet来跟踪字符的出现,另一种使用哈希映射来优化查找过程。这两种方法都通过移动左右指针并更新最大子串长度来找到最长无重复子串。
摘要由CSDN通过智能技术生成

最长无重复子串

public class Solution {
    /**
     * @param s: a string
     * @return: an integer
     */
    public int lengthOfLongestSubstring(String s) {
        // write your code here
        Set<Character> set = new HashSet<>();
        if (s == null || s.length() == 0) {
            return 0;
        }
        int max = 0;
        int right = 0;
        for (int i = 0; i < s.length(); i++) {
            while (right < s.length() && !set.contains(s.charAt(right))) {
                set.add(s.charAt(right++));
                max = Math.max(max, right - i);
            }
            set.remove(s.charAt(i));
        }
        return max;
    }
}


public class Solution {
    /**
     * @param s: a string
     * @return: an integer
     */
    public int lengthOfLongestSubstring(String s) {
        // write your code here
        if (s == null || s.length() == 0) {
       	return 0;
       }

       int i = 0;
       int j = 0;
       int ans = 0;
       int[] map = new int[256];
       for (i = 0; i < s.length(); i++) {
       	while (j < s.length() && map[s.charAt(j)] == 0) {
       		map[s.charAt(j)] = 1;
       		ans = Math.max(ans, j - i + 1);
       		j++;
       	}
       	map[s.charAt(i)] = 0;
       } 
       return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值