Given two strings, write a method to decide if one is a permutation of the other.
abcd
is a permutation ofbcad
, butabbe
is not a permutation ofabe
Here permutation means one arrangement of the characters.
Analysis:
This problem is very similar to the one about valid anagrams. Basically an array to hold the number of occurrence of each character. Then check whether the result to be zero in each cell of the array. If it’s, then yes, otherwise no.
public class Solution { /** * @param A a string * @param B a string * @return a boolean */ public boolean stringPermutation(String A, String B) { // Create a table to hold the occurences of each char int[] counter = new int[200]; for (int i = 0; i < A.length(); i++) { counter[A.charAt(i)]++; } for (int i = 0; i < B.length(); i++) { counter[B.charAt(i)]--; } for (int cnt: counter) { if (cnt != 0) { return false; } } return true; } }