Cracking the Coding Interview Q1.3

本文介绍了一种用于判断两个字符串是否为彼此的排列的方法。通过使用一个长度为256的整型数组来计数每个字符出现的次数,该方法能够有效地确定两个字符串是否包含相同的字符及其数量。

My Solution:

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

}


Solutions:

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;
	}


转载于:https://my.oschina.net/jdflyfly/blog/220117

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值