1.3

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

// 关键点1:Assume it is case sensitive and whitespace is significant. "god      "is different from "dog"

// 关键点2:If length different, then different.

// 方法1:Sort and Compare

// 方法2:Check if two have identical character counts. [注意:check whether character set is ASCII].

public class C1_1 {
	
	public static String sort(String s) {
		char[] s_array = s.toCharArray();
		java.util.Arrays.sort(s_array);
		return new String(s_array);
	}

	public static boolean permutation(String s, String t) {
		return sort(s).equals(sort(t));
	}

	public static boolean anagram(String s, String t) {
		if (s.length() != t.length())  return false; //如果长度不等,立刻返回false
		
		int[] set = new int[256];
		char[] s_array = s.toCharArray();
		for (char c : s_array) { // count number of each char in s.
			set[c]++;  
		}

		for (int i = 0; i < t.length(); i++) {
			int c = (int) t.charAt(i);
		    if (--set[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];
		System.out.println(word1 + ", " + word2 + ": " + permutation(word1, word2)+","+anagram(word1, word2));
	}
}
}
//结果
apple, papel: true,true
carrot, tarroc: true,true
hello, llloh: false,false



 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值