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;
    	}
    
    }
    



  • 相关阅读:
    从string类的实现看C++类的四大函数 [写的很好]
    毕业5年决定你的命运
    git push 原因以及问题!
    poj 1195 Mobile phones 夜
    poj 2886 Who Gets the Most Candies 夜
    poj Asimple Problem With Integers 夜
    poj 2750 Potted Flower 夜
    poj 2528 Mayor's posters 夜
    poj 2777 Count Color 夜
    poj 2482 Stars in Your Window 夜
  • 原文地址:https://www.cnblogs.com/xiaoqiangzhaitai/p/5429442.html
Copyright © 2011-2022 走看看