力扣:无重复字符最长子串

目录

一、问题描述

二、解决路线

三、代码实现


一、问题描述

二、解决路线

  采用滑动窗口法解决问题,相比较暴力解法的优化点:

  1. 窗口右端索引j,不用向前重复移动,时间复杂度O(N)。
  2. Map中存储键值对,值对应字符索引,每一次移动窗口左端索引时,取最新重复元素的位置,不需要清除map集合。

三、代码实现

package demo1;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class LengthOfLongestSubstringPlus {
	public int lengthOfLongestSubstring(String s) {
		int n = s.length();
		int max = 0;
        Map<Character, Integer> map = new HashMap<>(); 
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            max = Math.max(max, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return max;
	}
	
	public static void main(String[] args) {
		
	LengthOfLongestSubstringPlus l = new LengthOfLongestSubstringPlus();
	Scanner sc = new Scanner(System.in);
	int max = 0;
	String str;
	System.out.println("输入str");
    str = sc.nextLine();
    max = l.lengthOfLongestSubstring(str);
    System.out.println("max = " + max);
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值