Topic: Given two strings, write a method to decide if one is a permutation of the other.
// 关键点1:Assume it is case sensitive and whitespace is significant. "god "is different from "dog"
// 关键点2:If length different, then different.
// 方法1:Sort and Compare
// 方法2:Check if two have identical character counts. [注意:check whether character set is ASCII].
public class C1_1 {
public static String sort(String s) {
char[] s_array = s.toCharArray();
java.util.Arrays.sort(s_array);
return new String(s_array);
}
public static boolean permutation(String s, String t) {
return sort(s).equals(sort(t));
}
public static boolean anagram(String s, String t) {
if (s.length() != t.length()) return false; //如果长度不等,立刻返回false
int[] set = new int[256];
char[] s_array = s.toCharArray();
for (char c : s_array) { // count number of each char in s.
set[c]++;
}
for (int i = 0; i < t.length(); i++) {
int c = (int) t.charAt(i);
if (--set[c] < 0) { // 注意这个部分是比较两个数组是否相等,用的是--已有数组
return false;
}
}
return true;
}
public static void main(String[] args) {
String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
for (String[] pair : pairs) {
String word1 = pair[0];
String word2 = pair[1];
System.out.println(word1 + ", " + word2 + ": " + permutation(word1, word2)+","+anagram(word1, word2));
}
}
}
//结果
apple, papel: true,true
carrot, tarroc: true,true
hello, llloh: false,false