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


    题目:假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,比如: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;
    	}
    
    }
    



  • 相关阅读:
    终于成功发布我的博客园处女贴,不过,真的颇费周章,两个htmleditor都非常不好用~~
    全文本代码着色(带源码和示例)
    BlogBench Ver 1.0 发布
    [在windows上使用Unix工具]cygwin
    Linux下压缩与解压
    Linux设置界面或命令行启动
    perl模块安装
    Linux下patch的制作和应用
    TAR命令参数详解
    在windows上使用Sysinternals工具
  • 原文地址:https://www.cnblogs.com/xiaoqiangzhaitai/p/5637484.html
Copyright © 2020-2023  润新知