Solving String Permutation Problems in Java

Question:

Given two strings A and B, check if they can be rearranged to match (i.e., check if they are permutations of each other).

Solution:

import java.util.Arrays;

public class Solution {
    public int permuteStrings(String A, String B) {
        if (A == null || B == null || A.length() != B.length()) {
            return 0;
        }
        char A1[] = A.toCharArray();
        Arrays.sort(A1);

        char B1[] = B.toCharArray();
        Arrays.sort(B1);

        return Arrays.equals(A1, B1) ? 1 : 0;
    }
}

Explanation:

  1. Checking for Null or Unequal Length:

    • If either string is null or if their lengths are not equal, return 0 because they can't be permutations.
  2. Converting Strings to Character Arrays:

    • char A1[] = A.toCharArray(); converts the first string to a character array.

    • char B1[] = B.toCharArray(); converts the second string to a character array.

  3. Sorting the Character Arrays:

    • Arrays.sort(A1); sorts the character array of the first string.

    • Arrays.sort(B1); sorts the character array of the second string.

  4. Comparing the Sorted Arrays:

    • return Arrays.equals(A1, B1) ? 1 : 0; checks if the sorted arrays are equal. If they are, return 1; otherwise, return 0.

What I Learned:

  • Difference Between Reference and Content Equality:

    • Arrays.equals(A1, B1) checks if two arrays have the same content, not just if they reference the same object.
  • Input Validation and Handling Edge Cases:

    • It's important to handle null inputs and cases where the strings have different lengths. This prevents unnecessary operations and potential errors.
0
Subscribe to my newsletter

Read articles from Sarthak Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sarthak Kulkarni
Sarthak Kulkarni