java: add «1405. Longest Happy String»

URL:	https://leetcode.com/problems/longest-happy-string/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-10-16 23:37:24 +02:00
parent d7ed4d9aeb
commit 151eb4878b
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,36 @@
class Solution {
private char tryAppend(int[] allowed, int[] trailing, char letter) {
int i = letter - 'a';
if ((allowed[i] >= allowed[(i + 1) % 3]
&& allowed[i] >= allowed[(i + 2) % 3]
&& trailing[i] != 2)
|| (allowed[i] > 0 && (trailing[(i + 1) % 3] == 2 || trailing[(i + 2) % 3] == 2))) {
--allowed[i];
++trailing[i];
trailing[(i + 1) % 3] = 0;
trailing[(i + 2) % 3] = 0;
return letter;
}
return '\0';
}
public String longestDiverseString(int a, int b, int c) {
var longest = new StringBuilder();
var allowed = new int[] {a, b, c};
var trailing = new int[3];
for (int i = a + b + c; i > 0; --i) {
for (var letter : new char[] {'a', 'b', 'c'}) {
var toAppend = tryAppend(allowed, trailing, letter);
if (toAppend != '\0') {
longest.append(letter);
break;
}
}
}
return longest.toString();
}
}