关于腾讯的一道字符串匹配的面试题

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

  1. >>> sorted('abcda') == sorted('adabc')
  2. True

复制代码Geek的玩法不少,除了有人先提到的上面作法,我还想到如下方法也挺Geek:code

  1. >>> from collections import Counter
  2. >>> Counter('abcda') == Counter('adabc')
  3. True

复制代码 (Counter类在Python 2.7里被新增进来)

看看结果,是同样的:htm

  1. >>> Counter('abcda')
  2. Counter({'a': 2, 'c': 1, 'b': 1, 'd': 1})
  3. >>> Counter('adabc')
  4. Counter({'a': 2, 'c': 1, 'b': 1, 'd': 1})

复制代码 另外,能够稍微格式化输出结果看看,用到了Counter类的elements()方法:blog

  1. >>> list(Counter('abcda').elements())
  2. ['a', 'a', 'c', 'b', 'd']
  3. >>> list(Counter('adabc').elements())
  4. ['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

相关文章
相关标签/搜索