1.3 Whether Permutation

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.");
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值