[leetcode] 984. String Without AAA or BBB

网友投稿 242 2022-08-27

[leetcode] 984. String Without AAA or BBB

Description

Given two integers a and b, return any string s such that:

s has length a + b and contains exactly a ‘a’ letters, and exactly b ‘b’ letters,The substring ‘aaa’ does not occur in s, andThe substring ‘bbb’ does not occur in s.

Example 1:

Input: a = 1, b = 2Output: "abb"Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

Input: a = 4, b = 1Output: "aabaa"

Constraints:

0 <= a, b <= 100It is guaranteed such an s exists for the given a and b.

分析

题目的意思是:给定a的数量,b的数量,组成一个字符串,要求连续a或者连续b的数量不超过3.

我参考了一下答案,直觉的求解释选择当前所剩最多的待写字母写入字符串中。举一个例子,如果 a= 6, b = 2,那么我们期望写出 ‘aabaabaa’用flag标识变量控制当前需要选择的字母就行了,如果flag为True,则选择’a’,否则选择’b’选择’a’的情况是a的长度大于b,或者res结果里面最后连续两个字符是’b’,否则就需要选择’a’

代码

class Solution: def strWithout3a3b(self, a: int, b: int) -> str: res='' flag=False while(a>0 or b>0): if(len(res)>=2 and res[-1]==res[-2]): if(res[-1]=='b'): flag=True else: flag=False else: if(a>b): flag=True else: flag=False if(flag): res+='a' a-=1 else: res+='b' b-=1 return res

参考文献

​​不含 AAA 或 BBB 的字符串​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:《奇迹·笨小孩》和《四海》的差异化营销!
下一篇:[leetcode] 1536. Minimum Swaps to Arrange a Binary Grid
相关文章

 发表评论

暂时没有评论,来抢沙发吧~