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
, and - The substring
'bbb'
does not occur ins
.
Example 1:
Input: a = 4, b = 1
Output: "aabaa"
Approach
Java
public class WithoutAAAorBBB {public static void main(String[] args) {int a = 4, b = 1;System.out.println(strWithout3a3b(a, b));}static String strWithout3a3b(int A, int B) {String res = "";while (A > 0 || B > 0) {if (res.length() >= 2 && res.charAt(res.length() - 1) == 'a'&& res.charAt(res.length() - 2) == 'a') {res += 'b';B--;} else if (res.length() >= 2 && res.charAt(res.length() - 1) == 'b'&& res.charAt(res.length() - 2) == 'b') {res += 'a';A--;} else {if (A > B) {res += 'a';A--;} else {res += 'b';B--;}}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;string strWithout3a3b(int A, int B){string res="";while(A||B){if(res.size()>=2&&res[res.size()-1]=='a'&&res[res.size()-2]=='a'){res+='b';B--;}else if(res.size()>=2&&res[res.size()-1]=='b'&&res[res.size()-2]=='b'){res+='a';A--;}else{if(A>B){res+='a';A--;}else{res+='b';B--;}}}return res;}int main(){int a=4,b=1;cout<<strWithout3a3b(a,b);return 0;}
No comments:
Post a Comment