Algorithm


Problem Name: 984. 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 = 1, b = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

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

 

Constraints:

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

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const strWithout3a3b = function (a, b) {
  let res = ''

  while(a > 0 || b > 0) {
    if(endsWith(res, 'aa')) {
      res += 'b'
      b--
    } else if(endsWith(res, 'bb')) {
      res += 'a'
      a--
    } else if(a >= b) {
      res += 'a'
      a--
    } else {
      res += 'b'
      b--
    }
  }

  return res

  function endsWith(str, sub) {
    let i = str.length - 1, j = sub.length - 1
    for(; i >=0 && j >= 0;i--,j--) {
      if(str[i] !== sub[j]) return false
    }
    if(j >= 0) return false

    return true
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = 1, b = 2

Output

x
+
cmd
"abb"

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def strWithout3a3b(self, A: int, B: int) -> str:
        if not A and not B: return ''
        if A >= B:
            a = 2 if A >= 2 else 1
            b = 2 if A - a - B < 1 and B >= 2 else 1 if B else 0
            return a * 'a' + b * 'b' + self.strWithout3a3b(A - a, B - b)
        else:
            b = 2 if B >= 2 else 1
            a = 2 if B - b - A < 1 and A >= 2 else 1 if A else 0
            return b * 'b' + a * 'a' + self.strWithout3a3b(A - a, B - b)
            
Copy The Code & Try With Live Editor

Input

x
+
cmd
a = 1, b = 2

Output

x
+
cmd
"abb"
Advertisements

Demonstration


Previous
#983 Leetcode Minimum Cost For Tickets Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#985 Leetcode Sum of Even Numbers After Queries Solution in C, C++, Java, JavaScript, Python, C# Leetcode