Question:
假设两个字符串中所含有的字符和个数都相同我们就叫这两个字符串匹配,
比如:abcda和adabc,由于出现的字符个数都是相同,只是顺序不同,
所以这两个字符串是匹配的。要求高效!
Answer:
假定字符串中都是ASCII字符。如下用一个数组来计数,前者加,后者减,全部为0则匹配。
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的话,就更简单了:
- >>> sorted('abcda') == sorted('adabc')
- True
复制代码Geek的玩法很多,除了有人先提到的上面做法,我还想到以下方法也挺Geek:
- >>> from collections import Counter
- >>> Counter('abcda') == Counter('adabc')
- True
复制代码 (Counter类在Python 2.7里被新增进来)
看看结果,是一样的:
- >>> Counter('abcda')
- Counter({'a': 2, 'c': 1, 'b': 1, 'd': 1})
- >>> Counter('adabc')
- Counter({'a': 2, 'c': 1, 'b': 1, 'd': 1})
复制代码 另外,可以稍微格式化输出结果看看,用到了Counter类的elements()方法:
- >>> list(Counter('abcda').elements())
- ['a', 'a', 'c', 'b', 'd']
- >>> list(Counter('adabc').elements())
- ['a', 'a', 'c', 'b', 'd']
复制代码
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笔试题解答
http://www.cnblogs.com/lanxuezaipiao/p/3371224.html
来源:oschina
链接:https://my.oschina.net/u/568818/blog/78738