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:
parent
d7ed4d9aeb
commit
151eb4878b
1 changed files with 36 additions and 0 deletions
36
java/longest-happy-string.java
Normal file
36
java/longest-happy-string.java
Normal 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();
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue