0
点赞
收藏
分享

微信扫一扫

LeetCode_算法入门_无重复字符的最长子串

捌柒陆壹 2022-03-11 阅读 57

无重复字符的最长子串

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

示例 1:

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

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

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

(上述题目来源于LeetCode)

解法(滑动窗口)
class Solution {
    public int lengthOfLongestSubstring(String s) {
        //滑动窗口
        Map<Character,Integer> hashmap = new HashMap<>();
        int start = 0;
        int length = 0;
        int n = s.length();
        for(int end = 0;end < n;end++){
            char ch = s.charAt(end);
            if(hashmap.containsKey(ch)){
                start = Math.max(hashmap.get(ch) + 1,start);
            }
            length = Math.max(length,end - start + 1);
            hashmap.put(ch,end);
        }
        return length;
    }
}
举报

相关推荐

0 条评论