Build a Palindrome

  • + 0 comments

    Java, Brute Force TLE version

      public static String buildAPalindrome(String a, String b) {
        String longest = "";
        for (int ai = 0; ai < a.length(); ai++) {
          StringBuilder aBuilder = new StringBuilder();
          for (int aj = ai; aj < a.length(); aj++) {
            aBuilder.append(a.charAt(aj));
            for (int bi = 0; bi < b.length(); bi++) {
              StringBuilder bBuilder = new StringBuilder();
              for (int bj = bi; bj < b.length(); bj++) {
                bBuilder.append(b.charAt(bj));
                String palindrome = aBuilder.toString() + bBuilder.toString();
                if (!palindrome.equals(new StringBuilder(palindrome).reverse().toString())) continue;
                if (
                  palindrome.length() > longest.length()
                  || (palindrome.length() == longest.length() && palindrome.compareTo(longest) < 0)
                ) {
                  longest = palindrome;
                }
              }
            }
          }
        }
        return longest.isEmpty() ? "-1" : longest;
      }