您的位置:首页 > 职场人生

cracking the code interview problem 1.3

2014-02-19 04:05 351 查看
//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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 面试 algorithm