面试题>字符串匹配 小强斋

题目:假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,比如:abcda和adabc,由于出现的字符个数都是相同,只是顺序不同,所以这两个字符串是匹配的。给出判断两个字符串是否匹配的函数,要求高效!

方法思想:假定字符串中都是ASCII字符。如下用一个数组来计数,字符串中ascii码对应的位置数组值,前者加,后者减,全部为0则匹配。

import junit.framework.TestCase;

public class String_IsMatch extends TestCase {

	/**
	 * 假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,
	 * 比如:abcda和adabc,由于出现的字符个数都是相同,只是顺序不同,所以这两个字符串是匹配的。 给出判断两个字符串是否匹配的函数,要求高效!
	 */
	public void test() {
		String str1 = "aacde";
		String str2 = "aadec";
		boolean match = isMatch(str1, str2);
		System.out.println(match);

	}

	// 方法思想:假定字符串中都是ASCII字符。如下用一个数组来计数,字符串中ascii码对应的位置数组值,前者加,后者减,全部为0则匹配。
	public boolean isMatch(String str1, String str2) {
		if (str1 == null && str2 == null)
			return true;
		if (str1 == null || str2 == null)
			return false;
		if (str1.length() != str2.length())
			return false;

		int count[] = new int[256];
		for (int i = 0; i < str1.length(); i++) {
			count[str1.charAt(i)]++;
			count[str2.charAt(i)]--;
		}
		for (int i = 0; i < count.length; i++) {
			if (count[i] != 0)
				return false;
		}

		return true;
	}

}



原文地址:https://www.cnblogs.com/xiaoqiangzhaitai/p/5637484.html