數據結構和算法之最長的無重複字符串長度

思路

  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結果:
在這裏插入圖片描述

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