在給定的一個字符串中尋找出不包含重複字符的最長子串,使用滑動窗口進行實現。

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class Test1 {

	public static void main(String[] args) {
		// 初始化一個測試用的字符串
		String str = "asdfgrsefkkclgtdxdwee";

		StringBuilder sb = new StringBuilder();
		HashMap<Integer, String> map = new HashMap<>();

		int n = str.length();
		Set<Character> set = new HashSet<>();
		int max = 0, i = 0, j = 0;
		while (i < n && j < n) {
			if (!set.contains(str.charAt(j))) {
				char ss = str.charAt(j++);
				set.add(ss);
				sb.append(ss);
				max = max > j - i ? max : j - i;

				if (j == n) {
					map.put(sb.length(), sb.toString());
				}
			} else {
				map.put(sb.length(), sb.toString());
				set.remove(str.charAt(i++));
				sb.delete(0, 1);
			}
		}
		System.out.println("最大子串的長度:" + max);
		System.out.println("最大子串:" + map.get(max));
	}
}

祝願自己和大家可以在技術這條路上堅持下去,並且越走越遠!

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