From 4b1b202b41b1ba2d105bf4d04d601cfe6117f116 Mon Sep 17 00:00:00 2001 From: yennanliu Date: Wed, 13 Mar 2024 19:04:08 +0800 Subject: [PATCH] update 424 java --- .../LongestRepeatingCharacterReplacement.java | 36 +++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java b/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java index 09100f74..feece15d 100644 --- a/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java +++ b/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java @@ -2,12 +2,44 @@ // https://leetcode.com/problems/longest-repeating-character-replacement/ -import java.lang.reflect.Array; import java.util.HashSet; -import java.util.Set; +import java.util.HashMap; +import java.util.Map; public class LongestRepeatingCharacterReplacement { + // V0 + // IDEA : TWO POINTER + HASHMAP (modified by GPT) + // https://github.com/yennanliu/CS_basics/blob/master/leetcode_python/Hash_table/longest-repeating-character-replacement.py + public int characterReplacement(String s, int k) { + Map table = new HashMap<>(); + int res = 0; + int p1 = 0, p2 = 0; + + while (p2 < s.length()) { + char c = s.charAt(p2); + table.put(c, table.getOrDefault(c, 0) + 1); + p2++; + + while (p2 - p1 - getMaxValue(table) > k) { + char c1 = s.charAt(p1); + table.put(c1, table.get(c1) - 1); + p1++; + } + res = Math.max(res, p2 - p1); + } + return res; + } + + private int getMaxValue(Map map) { + int max = 0; + for (int value : map.values()) { + max = Math.max(max, value); + } + return max; + } + + // // V0 // // IDEA : SLIDING WINDOW // public int characterReplacement(String s, int k) {