Skip to content

2745. Construct the Longest New String 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int longestString(int x, int y, int z) {
    //"AB" can always be easily appended within the string.
    // Alternating "AA" and "BB" can be appended, creating a pattern like "AABB"
    // If x == y, we repeat the pattern "AABBAABB...AABB".
    // If x != y, the pattern becomes "AABBAABB...AABBAA" or "BBAABBAABB...AABB"
    const int mn = min(x, y);
    if (x == y)
      return (mn * 2 + z) * 2;
    return (mn * 2 + 1 + z) * 2;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public int longestString(int x, int y, int z) {
    final int mn = Math.min(x, y);
    if (x == y)
      return (mn * 2 + z) * 2;
    return (mn * 2 + 1 + z) * 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def longestString(self, x: int, y: int, z: int) -> int:
    # 'AB' can always be easily appended within the string.
    # Alternating 'AA' and 'BB' can be appended, creating a pattern like 'AABB'
    # If x == y, we repeat the pattern 'AABBAABB...AABB'.
    # If x != y, the pattern becomes 'AABBAABB...AABBAA' or 'BBAABBAABB...AABB'
    mn = min(x, y)
    if x == y:
      return (mn * 2 + z) * 2
    return (mn * 2 + 1 + z) * 2