码迷,mamicode.com
首页 > 其他好文 > 详细

滑动窗口-3. 无重复字符的最长子串

时间:2020-04-28 23:28:54      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:ati   tin   problem   长度   cte   sts   滑动窗口   long   with   

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

示例?1:

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

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

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

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

import java.util.HashMap;

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

滑动窗口-3. 无重复字符的最长子串

标签:ati   tin   problem   长度   cte   sts   滑动窗口   long   with   

原文地址:https://www.cnblogs.com/ZCWang/p/12797964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!