[LeetCode] 1405. Longest Happy String

A string is called happy if it does not have any of the strings 'aaa''bbb' or 'ccc' as a substring.

Given three integers ab and c, return any string s, which satisfies following conditions:

  • s is happy and longest possible.
  • s contains at most a occurrences of the letter 'a', at most b occurrences of the letter 'b' and at most c occurrences of the letter 'c'.
  • will only contain 'a''b' and 'c' letters.

If there is no such string s return the empty string "".

Example 1:

Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.

Example 2:

Input: a = 2, b = 2, c = 1
Output: "aabbc"

Example 3:

Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It's the only correct answer in this case.

Constraints:

  • 0 <= a, b, c <= 100
  • a + b + c > 0

最长快乐字符串。

如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。

给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:

s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-happy-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题其实是984题的升级版,984题只有 A 和 B 两个字母,这道题需要处理三个不同字母。

思路还是贪心。这里我们需要一个 StringBuilder,然后按字符一个个 append 组成最后的 output 字符串。我们优先 append 个数最多的字母,但是注意一次顶多 append 两个相同字母。同时,当次数最多的字母不能再用的时候,我们就 append 出现次数第二多的字母。最后还有一个 corner case 需要考虑,当出现次数最多的字母被 append 过两次之后,它有可能还是出现次数最多的字母,此时我们可以 append 另外两个字母。所以这里我们需要三个 counter 变量 A,B,C 来追踪目前已经连续 append 过几个字母了。当我们 append 某一个字母的时候,其他两个字母的 counter 需要归零。

时间O(n)

空间O(n) - StringBuilder

Java实现

 1 class Solution {
 2     public String longestDiverseString(int a, int b, int c) {
 3         StringBuilder sb = new StringBuilder();
 4         int size = a + b + c;
 5         int A = 0;
 6         int B = 0;
 7         int C = 0;
 8         for (int i = 0; i < size; i++) {
 9             if ((a >= b && a >= c && A != 2) || (a > 0 && B == 2) || (a > 0 && C == 2)) {
10                 sb.append('a');
11                 a--;
12                 A++;
13                 B = 0;
14                 C = 0;
15             } else if ((b >= a && b >= c && B != 2) || (b > 0 && A == 2) || (b > 0 && C == 2)) {
16                 sb.append('b');
17                 b--;
18                 B++;
19                 A = 0;
20                 C = 0;
21             } else if ((c >= a && c >= b && C != 2) || (c > 0 && A == 2) || (c > 0 && B == 2)) {
22                 sb.append('c');
23                 c--;
24                 C++;
25                 A = 0;
26                 B = 0;
27             }
28         }
29         return sb.toString();
30     }
31 }

 

相关题目

984. String Without AAA or BBB

1405. Longest Happy String

LeetCode 题目总结 

posted @ 2021-01-19 00:56  CNoodle  阅读(743)  评论(0编辑  收藏  举报