String Permutation
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
1 public class Solution { 2 /** 3 * @param A a string 4 * @param B a string 5 * @return a boolean 6 */ 7 public boolean stringPermutation(String A, String B) { 8 // Write your code here 9 if(A==null&&B==null){ 10 return true; 11 } else if (A==null||B==null||A.length()!=B.length()){ 12 return false; 13 } 14 Map<Character, Integer> a = new HashMap<Character, Integer>(); 15 16 for(char c : A.toCharArray()){ 17 if(!a.containsKey(c)) 18 a.put(c, 1); 19 else 20 a.put(c, a.get(c)+1); 21 22 //a.put(c, a.getOrDefault(c, 0) + 1); 23 } 24 for(char c : B.toCharArray()){ 25 if(!a.containsKey(c) || a.get(c)==0){ 26 return false; 27 } 28 a.put(c, a.get(c)-1); 29 } 30 return true; 31 } 32 }