package chapter1;
/*
* Q:given two string,check one of them can be got by another permutation again
* E:"abcdb","dcbab"->true
* S1:check the char and it's nums of two strings are same
* create two array which index maps value of char
* count the char's num
* check the char and num are same
* S2:sort two string,compare them are equal
*/
public class Q2 {
public static boolean CheckPermutation1(String s1,String s2) {
int [] A=new int[128];
int[]B=new int[128];
if(s1.length()!=s2.length())return false;
for(int i=0;i<s1.length();i++) {
int v1=s1.charAt(i);
int v2=s2.charAt(i);
A[v1]++;
B[v2]++;
}
for(int i=0;i<A.length;i++) {
if(A[i]!=B[i])return false;
}
return true;
}
public static String sort(String s) {
char[]content=s.toCharArray();
java.util.Arrays.sort(content);
return new String(content);
}
public static boolean CheckPermutation2(String s1,String s2) {
return sort(s1).equals(sort(s2));
}
public static void main(String[] args) {
//String[]words= {"abcdb","dcbab","abbd"};
//System.out.println(words[1]);
//System.out.println(words[0]+","+words[1]+":"+CheckPermutation1(words[0], words[1]));
//System.out.println(words[0]+","+words[2]+":"+CheckPermutation1(words[0], words[2]));
String[][]pairs= {{"abcdb","dcbab"},{"abcdbd","dcbab"},{"aadf","knag"}};
for(String[]pair:pairs) {
String word1=pair[0];
String word2=pair[1];
long startTime1 = System.nanoTime(); //获取开始时间
System.out.println(word1+","+word2+":"+CheckPermutation1(word1, word2)); //测试的代码段
long endTime1 = System.nanoTime(); //获取结束时间
System.out.println("程序1运行时间:" + (endTime1 - startTime1) + "ms"); //输出程序运行时间
long startTime2 = System.nanoTime(); //获取开始时间
System.out.println(word1+","+word2+":"+CheckPermutation2(word1, word2)); //测试的代码段
long endTime2 = System.nanoTime(); //获取结束时间
System.out.println("程序2运行时间:" + (endTime2 - startTime2) + "ms"); //输出程序运行时间
System.out.println("\n");
}
}
}