cracking the code interview problem 1.3

本文介绍了一种方法来判断两个字符串是否互为变位词,即它们是否可以通过重新排列字符而成为彼此。讨论了使用排序和不使用排序两种情况下的时间复杂度,并提供了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Given two Strings,write a method to decide if one is a permutation of the other.
//ask what the complexity of time, can we use sort first?
//if we can use sort:
public class Solution {
	public static String sortString(String s) {
		char[] c = s.toCharArray();
		java.util.Arrays.sort(c);
		String res = new String(c);
		return res;
	}

	public static boolean isPermutation(String s1, String s2) {
		return sortString(s1).equals(sortString(s2));
	}

	// if we are not allowed to use sort, we may ask how large the character set
	// is? ASCII?
	public static boolean isPermutation2(String s1, String s2) {
		if(s1.length()!=s2.length())
			return false;
		int[] letters = new int[256];
		char[] charArray = s1.toCharArray();
		for (char c : charArray) { // count number of each char in s.
			letters[c]++;  
		}
		  
		for (int i = 0; i < s2.length(); i++) {
			int c = (int) s2.charAt(i);
		    if (--letters[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];
			boolean anagram = isPermutation(word1, word2);
			boolean anagram2 = isPermutation2(word1, word2);
			System.out.println(word1 + ", " + word2 + ": " + anagram);
			System.out.println(word1 + ", " + word2 + ": " + anagram2);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值