LeetCode——3.无重复字符的最长子串

LeetCode题目地址
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目

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

示例1:

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

示例2:

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

示例3:

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

工具:利用Math.max(Obj a,Obj b)ab两个元素中挑选出的最大一个

方法1:利用HashMap

思路:
  1. 判断字符串为空的情景;
  2. 定义HashMap<Character,Integer>数据类型,Character记录每个字符的,Integer记录每个字符的最新的位置;j来标记不重复字符串的起始位置;
  3. 遍历字符串s,如果map不包含,则存放该字符以及当前索引位置,定义res变量,利用Math.max()函数取(res, i-j+1)中的最大值;如果map包含该字符串,则利用j = Math.max(j,map.get(s.charAt(i))+1),让j指向下一个不重复字符的起始位置。

注:每一次利用res = Math.max(res, i-j+1);计算当前字符串的长度,并与当前存储的最大值res比较,取最大的一个,从而保证res动态更新;
j = Math.max(j,map.get(s.charAt(i))+1);j的取值不能直接使用j =map.get(s.charAt(i))+1;,因为这种写法没有把abba的情景考虑在内

具体代码:
public class Solution3 {

    public static int lengthOfLongestSubstring(String s) {
        if (s == null ||s.length() ==0)
            return 0;
        HashMap<Character,Integer> map = new HashMap<>();
        int res =0;
        for (int i=0,j=0; i<s.length() ; i++){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            res = Math.max(res, i-j+1);
        }
        return res;
    }

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


}

方法2:利用HashSet(推荐)

思路:

利用HashSet的元素的不重复特性,HashSet中能存放元素最长的时候,就是无重复字符的最长子串的时候

具体代码:
public class Solution3 {

    public static int lengthOfLongestSubstring2(String s) {
        if (s == null ||s.length() ==0)
            return 0;
        HashSet<Character> set = new HashSet<>();
        int res =0;
        for (int i=0,j=0; i<s.length() ; i++){
            if (set.contains(s.charAt(i))){
                set.remove(s.charAt(j++));
            }else {
                set.add(s.charAt(i));
                res = Math.max(res, set.size());
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring2("abcabccd"));;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值