#2745
Construct the Longest New String
MediumApproaches
💡
Intuition
Time UnknownSpace Unknown
In the brute force approach, we can generate all possible combinations of the strings 'AA', 'BB', and 'AB', and check each combination to see if it violates the constraints of containing 'AAA' or 'BBB'. This method is straightforward but inefficient.
⚙️
Algorithm
3 steps- 1Step 1: Generate all possible combinations of 'AA', 'BB', and 'AB'.
- 2Step 2: For each combination, check if it contains 'AAA' or 'BBB'.
- 3Step 3: Keep track of the maximum length of valid combinations.
solution.py11 lines
1# Full working Python code
2from itertools import permutations
3
4def max_length_brute_force(x, y, z):
5 strings = ['AA'] * x + ['BB'] * y + ['AB'] * z
6 max_length = 0
7 for perm in set(permutations(strings)):
8 combined = ''.join(perm)
9 if 'AAA' not in combined and 'BBB' not in combined:
10 max_length = max(max_length, len(combined))
11 return max_lengthSolutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.