1.3 Whether Permutation

来源:互联网 发布:公司销售网络介绍 编辑:程序博客网 时间:2024/06/13 11:49

1.3 Given two strings, write a method to decide if one is a permutation of the other.


1. ask question

Whether the anagram comparison is case sensitive? Is whitespace significant?

Is God an anagram of dog? Is "god   " is different from "odg"?

If two string have different lengths then they can't be anagrams.


2. Solution: sort the strings

If two strings are anagrams, they must have the same characters, but in different orders. 

Sorting the strings will put the characters from two anagrams in the same order. 

We just need to compare the sorted version of the strings.

This algorithm is clean and easy to understand but not very efficiency. 


3. Solution: Check if the two strings have identical character counts

The definition of an anagram is two words with the same character counts.

We simply iterate through this code, counting how many times each character appears.

Then compare the two arrays.

class Permutation{  public static void main(String[] args){    String s1 = "abcb";    String s2 = "bbca";    permutation(s1,s2);    permutation2(s1,s2);  }    public static void permutation(String str1, String str2){    if (str1.length() != str2.length()){      System.out.println("1.Not permutation of the other.");      return;    }        if ( sort(str1).equals(sort(str2)) ) // sort s1 and s2 and compare      System.out.println("1.Yes permutation of the other.");  }    public static String sort(String str){ // sort a string return a string    char[] temp = str.toCharArray();    java.util.Arrays.sort(temp); // use JAVA sort    return new String(temp);  }    public static void permutation2(String str1, String str2){    if (str1.length() != str2.length()){       System.out.println("2.Not permutation of the other.");       return;    }          int[] check = new int[256]; // assumption if Unicode with a large array     char[] temp = str1.toCharArray();     for (char c : temp)  // count number of each char in temp       check[c-'a']++; // careful with ArrayOutBound         for (int i=0; i< str2.length(); i++){       int m = (int)str2.charAt(i);       if (--temp[m-'a'] < 0){         System.out.println("2.Not permutation of the other.");         return;       }     }     System.out.println("2.Yes permutation of the other.");  }}


原创粉丝点击