Skip to content

Commit

Permalink
update 424 java
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Mar 14, 2024
1 parent 3374619 commit 07bc7ea
Showing 1 changed file with 33 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Character, Integer> 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<Character, Integer> 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<Character, Integer> table = new HashMap<>();
int res = 0;
int p1 = 0, p2 = 0;
Expand All @@ -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++;
Expand All @@ -31,7 +61,7 @@ public int characterReplacement(String s, int k) {
return res;
}

private int getMaxValue(Map<Character, Integer> map) {
private int getMaxValue_0(Map<Character, Integer> map) {
int max = 0;
for (int value : map.values()) {
max = Math.max(max, value);
Expand Down

0 comments on commit 07bc7ea

Please sign in to comment.