数据结构和算法之最长的无重复字符串长度

思路

  1. 利用滑动窗口
  2. 右窗口遍历数组,如果值不在滑动窗口内,当前字符可以加进来;如果在的话,只需要移动左窗口指针,然后计算窗口大小
  3. 利用一个散列表记录每个字符串的下标位置

上代码:

package com.zyblue.fastim.common.algorithm;

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

/**
 * 最大字符串长度
 * Author : BlueSky 2019.11.05
 * exe:  asddww  asd 3         pwwkew wke 3
 */
public class MaxStrLength {
    public static int maxLength(String str){
        int res = 0;
        int len = str.length();
        // 字符串和下标的映射
        Map<Character, Integer> map = new HashMap<Character, Integer>(8);
        for(int head = 0, tail = 0;tail < len; tail++){
            // 如果窗口内遇到相同的字符
            if(map.containsKey(str.charAt(tail))){
                // 移动前指针
                head = map.get(str.charAt(tail));
            }
            // 计算窗口内的大小
            res = Math.max(res, tail - head);
            map.put(str.charAt(tail), tail);
        }

        return res;
    }

    public static void main(String[] args) {
        int i = maxLength("abcabcbb");
        System.out.println("maxLength:" + i);

    }
}

leetcode结果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章