思路
- 利用滑動窗口
- 右窗口遍歷數組,如果值不在滑動窗口內,當前字符可以加進來;如果在的話,只需要移動左窗口指針,然後計算窗口大小
- 利用一個散列表記錄每個字符串的下標位置
上代碼:
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結果: