zoukankan      html  css  js  c++  java
  • 面试题>字符串匹配

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



  • 相关阅读:
    分享一个关于Cookie做的实验结果
    使用jest进行单元测试
    【转载】为什么单反镜头做不小,镜头越好越重呢?
    【转载】解读手机摄像头
    【转载】2019中国机器视觉产业全景图谱
    【行业】视觉传感器
    图像质量测评
    COM口了解下
    dbus-python的API及示例
    QtDbus的API及示例
  • 原文地址:https://www.cnblogs.com/xqzt/p/5637167.html
Copyright © 2011-2022 走看看