Longest Happy String LeetCode solution in Java

1
/*
2
The idea behid this problem
3
1. Here we start by taking the size as the sum of a, b, c.
4
2. Then we use 3 variables A, B, C to count the occurance of a, b, c.
5
3. Now we iterate until the size, and
6
-> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.
7

8
4. Finally return the string.
9
*/
10
class Solution {
11
public String longestDiverseString(int a, int b, int c) {
12
int totalSize = a + b + c;
13
int A = 0;
14
int B = 0;
15
int C = 0;
16
StringBuilder sb = new StringBuilder();
17
for (int i = 0; i < totalSize; i++) {
18
// checks a is largest and its count still < 2 or B and C =2 and there are still a that can be
19
// added
20
if ((a >= b && a >= c && A < 2) || (B == 2 && a > 0) || (C == 2 && a > 0)) {
21
sb.append("a");
22
a -= 1;
23
A += 1;
24
B = 0;
25
C = 0;
26
}
27
// check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be
28
// added
29
else if ((b >= a && b >= c && B < 2) || (A == 2 && b > 0) || (C == 2 && b > 0)) {
30
sb.append("b");
31
b -= 1;
32
B += 1;
33
A = 0;
34
C = 0;
35
}
36
// checks c is largest and its count still < 2 or B and A = 2 and there are still c that can
37
// be added
38
else if ((c >= a && c >= b && C < 2) || (A == 2 && c > 0) || (B == 2 && c > 0)) {
39
sb.append("c");
40
c -= 1;
41
C += 1;
42
A = 0;
43
B = 0;
44
}
45
}
46
return sb.toString();
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0