String Permutation

Problem

Given two strings, write a method to decide if one is a permutation of the other.

Example

abcd is a permutation of bcad, but abbe is not a permutation of abe

Solution

If one string is a permutation of the other, they must have the same number of each characters, so you can sort the two strings then compare. Or count how many times each character appears in each string and compare the counts.

Code - Java

public class Solution {
    /**
     * @param A a string
     * @param B a string
     * @return a boolean
     */
    public boolean stringPermutation(String A, String B) {
        char[] a = A.toCharArray();
        char[] b = B.toCharArray();

        Arrays.sort(a);
        Arrays.sort(b);

        return new String(a).equals(new String(b));
    }
}