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

时间:2022-04-28
本文章向大家介绍关于腾讯的一道字符串匹配的面试题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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的话,就更简单了:

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

复制代码Geek的玩法很多,除了有人先提到的上面做法,我还想到以下方法也挺Geek:

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

复制代码 (Counter类在Python 2.7里被新增进来) 看看结果,是一样的:

  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()方法:

  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

精选30道Java笔试题解答

http://www.cnblogs.com/lanxuezaipiao/p/3371224.html