From 07bc7eadf0c034c6bfd42a0a5873cfb6ea9d1e49 Mon Sep 17 00:00:00 2001 From: yennanliu Date: Thu, 14 Mar 2024 09:20:55 +0800 Subject: [PATCH] update 424 java --- .../LongestRepeatingCharacterReplacement.java | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java b/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java index feece15d..d10d85c8 100644 --- a/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java +++ b/leetcode_java/src/main/java/LeetCodeJava/HashTable/LongestRepeatingCharacterReplacement.java @@ -9,9 +9,39 @@ public class LongestRepeatingCharacterReplacement { // V0 - // IDEA : TWO POINTER + HASHMAP (modified by GPT) + // IDEA : TWO POINTER + HASHMAP + FOR LOOP // 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; + + for (int p2 = 0; p2 < s.length(); p2++) { + char c = s.charAt(p2); + table.put(c, table.getOrDefault(c, 0) + 1); + + while ( (p2 - p1 + 1) - getMaxValue(table) > k) { + char c1 = s.charAt(p1); + table.put(c1, table.get(c1) - 1); + p1++; + } + res = Math.max(res, p2 - p1 + 1); + } + return res; + } + + private int getMaxValue(Map map) { + int max = 0; + for (int value : map.values()) { + max = Math.max(max, value); + } + return max; + } + + // 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_0(String s, int k) { Map table = new HashMap<>(); int res = 0; int p1 = 0, p2 = 0; @@ -21,7 +51,7 @@ public int characterReplacement(String s, int k) { table.put(c, table.getOrDefault(c, 0) + 1); p2++; - while (p2 - p1 - getMaxValue(table) > k) { + while (p2 - p1 - getMaxValue_0(table) > k) { char c1 = s.charAt(p1); table.put(c1, table.get(c1) - 1); p1++; @@ -31,7 +61,7 @@ public int characterReplacement(String s, int k) { return res; } - private int getMaxValue(Map map) { + private int getMaxValue_0(Map map) { int max = 0; for (int value : map.values()) { max = Math.max(max, value);