Leetcode Hot 100刷题记录 -Day6(滑动窗口)

无重复字符的最长子串

问题描述:

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

示例 1:

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

示例 2:

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

示例 3:

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

解题思路:

3. 无重复字符的最长子串 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/longest-substring-without-repeating-characters/solutions/7399/hua-jie-suan-fa-3-wu-zhong-fu-zi-fu-de-zui-chang-z/?envType=study-plan-v2&envId=top-100-liked

// hot7:无重复字符的最长子串

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int start =-1;
        int end =0;
        int ans =0;
        HashMap<Character,Integer> hashMap = new HashMap<>();
        for(;end <s.length();end++){
            if (hashMap.containsKey(s.charAt(end))){
                start = Math.max(start,hashMap.get(s.charAt(end)));
            }
            hashMap.put(s.charAt(end),end);
            ans = Math.max(ans,end-start);
        }
        return ans;
    }
}

//带有输入输出
// hot7:无重复字符的最长子串
import java.util.HashMap;

public class hot7_lengthOfLongestSubstring {
    public int lengthOfLongestSubstring(String s){
        int start =-1;
        int end =0;
        int ans =0;
        HashMap<Character,Integer> hashMap = new HashMap<>();
        for(;end <s.length();end++){
            if (hashMap.containsKey(s.charAt(end))){
                start = Math.max(start,hashMap.get(s.charAt(end)));
            }
            hashMap.put(s.charAt(end),end);
            ans = Math.max(ans,end-start);
        }
        return ans;
    }

    public static void main(String[] args){
        hot7_lengthOfLongestSubstring hot7LengthOfLongestSubstring = new hot7_lengthOfLongestSubstring();
        String s = "abcabcbb";
        System.out.println("输入 = " + s);
        int result = hot7LengthOfLongestSubstring.lengthOfLongestSubstring(s);
        System.out.println("输出:" + result);
    }
}

知识点总结:

  • s.charAt(指针):获取当前指针所指向的字符串中的字母

  • start初始化为-1:因为若是start和end都初始化为0时,当字符串中只有一个字母("b")时,end指针指向b时,其对应的下标为0,而end要小于字符串的长度1,所以end最大为0,这就导致其在计算最长子串时变为0-0=0,所以在初始化左指针start时,应该设为-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值