String Without AAA or BBB

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, and
  • The substring 'bbb' does not occur in s.

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 Aint 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 Aint 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