LC 984. String Without AAA or BBB
Posted ethanhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 984. String Without AAA or BBB相关的知识,希望对你有一定的参考价值。
Given two integers A
and B
, return any string S
such that:
S
has lengthA + B
and contains exactlyA
‘a‘
letters, and exactlyB
‘b‘
letters;- The substring
‘aaa‘
does not occur inS
; - The substring
‘bbb‘
does not occur inS
.
Example 1:
Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.
Example 2:
Input: A = 4, B = 1
Output: "aabaa"
Note:
0 <= A <= 100
0 <= B <= 100
- It is guaranteed such an
S
exists for the givenA
andB
.
Runtime: 0 ms, faster than 100.00% of C++ online submissions for String Without AAA or BBB.
Memory Usage: 753.7 KB, less than 100.00% of C++ online submissions for String Without AAA or BBB.
class Solution { public: string strWithout3a3b(int A, int B) { if(A <= B) { return helper("b","a", B, A); } return helper("a","b", A, B); } string helper(string more, string less, int m, int l){ string ret = ""; if( m - l > l) { //assert(m - l <= 3); for(int i=0; i<l; i++){ ret += more + more + less; } for(int i=0; i< m - l - l; i++) { ret += more; } } else { for(int i=0; i<m-l; i++) { ret += more + more + less; } for(int i=0; i<2*l-m; i++){ ret += more + less; } } return ret; } };
以上是关于LC 984. String Without AAA or BBB的主要内容,如果未能解决你的问题,请参考以下文章
LC 3. Longest Substring Without Repeating Characters
[LC] 131. Palindrome Partitioning
[GeeksForGeeks] Reverse a string without using any temporary variables
Leetcode 3. Longest Substring Without Repeating Characters(string 用法 水题)