//Given two Strings,write a method to decide if one is a permutation of the other.
//ask what the complexity of time, can we use sort first?
//if we can use sort:
public class Solution {
public static String sortString(String s) {
char[] c = s.toCharArray();
java.util.Arrays.sort(c);
String res = new String(c);
return res;
}
public static boolean isPermutation(String s1, String s2) {
return sortString(s1).equals(sortString(s2));
}
// if we are not allowed to use sort, we may ask how large the character set
// is? ASCII?
public static boolean isPermutation2(String s1, String s2) {
if(s1.length()!=s2.length())
return false;
int[] letters = new int[256];
char[] charArray = s1.toCharArray();
for (char c : charArray) { // count number of each char in s.
letters[c]++;
}
for (int i = 0; i < s2.length(); i++) {
int c = (int) s2.charAt(i);
if (--letters[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];
boolean anagram = isPermutation(word1, word2);
boolean anagram2 = isPermutation2(word1, word2);
System.out.println(word1 + ", " + word2 + ": " + anagram);
System.out.println(word1 + ", " + word2 + ": " + anagram2);
}
}
}
cracking the code interview problem 1.3
最新推荐文章于 2024-09-03 20:17:53 发布