String Without AAA or BBB Solutions in C++
Number 984
Difficulty Medium
Acceptance 37.8%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/string-without-aaa-or-bbb/// Author : Hao Chen// Date : 2019-01-29class Solution {public:string strWithout3a3b(int A, int B) {string result;while (true){// if A == B, then just simpley repeat "ab" pattern;if (A == B) {for ( int i=0; i<A; i++ ) {result += "ab";}break;}// if A+B less then 3 and A != B, which means A=1,2 && B=0 or A=0 && B=1,2if (A+B <3) {while ( A-- > 0 ) result += 'a';while ( B-- > 0 ) result += 'b';break;}// if A+B >=3 and A !=B// if A > B, then we need consume 'a' more than 'b'// So, only "aab" can be used.if ( A > B ) {result += "aab";A -= 2;B--;continue;}// if A > B, then we need consume 'b' more than 'a'// So, only "bba" can be used.if (B > A ){result += "bba";B-=2;A--;continue;}}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/string-without-aaa-or-bbb//// Author : liuyubobobo/// Time : 2019-01-26#include <iostream>#include <vector>using namespace std;/// Ad-Hoc/// Time Complexity: O(A + B)/// Space Complexity: O(1)class Solution {public:string strWithout3a3b(int A, int B) {if(A > B)return get_str(A - B, "a", B, "ab");return get_str(B - A, "b", A, "ba");}private:string get_str(int k1, const string& s1, int k2, const string& s2){string res = "";while(k1 -- && k2 --) res += s1 + s2;while(k2 --) res += s2;while(k1 --) res += s1;return res;}};int main() {return 0;}