Cracking the Coding Interview Q1.3

Write a method to decide if two strings are anagrams or not.

 

package chapter1;

/**
 * Write a method to decide if two strings are anagrams or not.
 * 
 * @author jd
 * 
 */
public class Q1_3 {
    /**
     * Assume the char set is extended ASCII, we check whether the two string
     * have identical counts for each char.
     */
    static boolean permutation(String a, String b) {
        if (a == null)
            return b == null;
        int[] count = new int[256];
        for (int i = 0; i < a.length(); i++) {
            count[a.charAt(i)]++;
        }

        //this part is so nice
        for (int i = 0; i < b.length(); i++) {
            count[b.charAt(i)]--;
            if (count[b.charAt(i)] < 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 = permutation(word1, word2);
            System.out.println(word1 + ", " + word2 + ": " + anagram);
        }
    }

}
View Code

 

Solution:

public static boolean permutation(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        
        int[] letters = new int[256];
         
        char[] s_array = s.toCharArray();
        for (char c : s_array) { // count number of each char in s.
            letters[c]++;  
        }
          
        for (int i = 0; i < t.length(); i++) {
            int c = (int) t.charAt(i);
            if (--letters[c] < 0) {
                return false;
            }
        }
          
        return true;
    }
View Code

 

转载于:https://www.cnblogs.com/jdflyfly/p/3821667.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值