1. 程式人生 > 其它 >Leecode no.3 無重複字元的最長子串

Leecode no.3 無重複字元的最長子串

package leecode;

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

/**
* 3. 無重複字元的最長子串
* 給定一個字串 s ,請你找出其中不含有重複字元的 最長子串 的長度。
*
*
* @author Tang
* @date 2021/12/7
*/
public class LengthOfLongestSubstring {

/**
* 滑動視窗方法
*
*
* @param s
* @return
*/
public int lengthOfLongestSubstring(String s) {
char[] all = s.toCharArray();

//初始化視窗
Map<Character, Integer> window = new HashMap<>();

//視窗左右指標
int left = 0;
int right = 0;

//當前視窗中不同元素的個數
int valid = 0;

int result = 0;

while(right < all.length) {
char c = all[right];
right++;

//視窗中沒有和c重複的值
if(!window.containsKey(c)) {
window.put(c, 1);
valid++;

//更新result
result = Math.max(result, valid);
continue;
}

//如果有重複元素則視窗左縮
//左縮到把c重複元素幹掉
while(window.containsKey(c)) {
char d = all[left];
left++;
window.remove(d);
valid--;
}

//最後把這個c加入視窗
window.put(c, 1);
valid++;
}
return Math.max(valid, result);
}

// /**
// * 迴圈遍歷方法
// * 迴圈元素,判斷以每個元素開頭的最長子串,更新result
// * @param s
// * @return
// */
// public int lengthOfLongestSubstring(String s) {
// if(s.equals(" ")) {
// return 1;
// }
//
//
// char[] all = s.toCharArray();
//
// int result = 0;
//
// Map<Character, Integer> map = null;
// for(int i = 0; i < all.length; i++) {
// map = new HashMap<>();
//
// for(int j = i; j < all.length; j++) {
// if(map.containsKey(all[j])) {
// break;
// }
// map.put(all[j], 1);
// result = Math.max(result, map.size());
// }
//
//
// }
//
// return result;
//
// }

public static void main(String[] args) {


}

}