Wednesday, March 18, 2015

Check permutations

Determine if two strings are permutations of each other.

Solution:
先把string转换成char[ ],  然后sort,如果sort后是一样的,说明是permutation。
public static void main(String[] args) {
  String str1 = "1234";
  String str2 = "4231";
  String str3 = "";
  String str4 = "1235";
  System.out.println("check str1 & str2: "+checkPermutations(str1, str2));
  System.out.println("check str1 & str3: "+checkPermutations(str1, str3));
  System.out.println("check str1 & str4: "+checkPermutations(str1, str4));

 }
 
 public static boolean checkPermutations(String str1, String str2) {
  char[] c1 = str1.toCharArray();
  char[] c2 = str2.toCharArray();
  
  Arrays.sort(c1);
  Arrays.sort(c2);
  
  return Arrays.equals(c1, c2);
 }

No comments:

Post a Comment