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); } } }
相关文章推荐
- cracking the code interview problem 1.1
- cracking the coding interview problem solution 1.3
- Cracking the code interview 1.3
- cracking the code interview——c++实现
- Replace all spaces in string with ' ' (Cracking the Code Interview)
- Cracking the Code Interview 4.3 Array to Binary Tree
- CrackingtheCodeInterview之中等难题
- cracking the code interview balanced tree python
- CrackingtheCodeInterview之数组与字符串
- cracking the coding interview No1.3
- CrackingtheCodeInterview之数学与概率
- cracking the coding interview problem solution 1.5
- Cracking the code interview总结
- Cracking The Coding Interview 3rd -- 1.3
- Cracking the Coding Interview Q1.3
- 笔记摘录——Cracking the code interview
- cracking the coding interview problem solution 1.8
- Cracking the code interview 1.6
- Cracking the code interview 面试题:两个数相加
- Cracking The Coding Interview 1.3