Question:html
假设两个字符串中所含有的字符和个数都相同咱们就叫这两个字符串匹配,python
好比:abcda和adabc,因为出现的字符个数都是相同,只是顺序不一样,面试
因此这两个字符串是匹配的。要求高效!数组
Answer:spa
假定字符串中都是ASCII字符。以下用一个数组来计数,前者加,后者减,所有为0则匹配。.net
static bool IsMatch(string s1, string s2) { if (s1 == null && s2 == null) return true; if (s1 == null || s2 == null) return false; if (s1.Length != s2.Length) return false; int[] check = new int[128]; foreach (char c in s1) { check[(int)c]++; } foreach (char c in s2) { check[(int)c]--; } foreach (int i in check) { if (i != 0) return false; } return true; }
若是使用python的话,就更简单了:unix
复制代码Geek的玩法不少,除了有人先提到的上面作法,我还想到如下方法也挺Geek:code
复制代码 (Counter类在Python 2.7里被新增进来)
看看结果,是同样的:htm
复制代码 另外,能够稍微格式化输出结果看看,用到了Counter类的elements()方法:blog
复制代码
REF:
http://blog.sina.com.cn/s/blog_5fe9373101011pj0.html
http://bbs.chinaunix.net/thread-3770641-1-1.html
http://topic.csdn.net/u/20120908/21/F8BE391F-E4F1-46E9-949D-D9A640E4EE32.html
http://blog.csdn.net/v_july_v/article/details/7974418
精选30道Java笔试题解答