美文网首页
LintCode_chapter1_section2_compa

LintCode_chapter1_section2_compa

作者: 穆弋 | 来源:发表于2015-11-05 16:16 被阅读65次

容易
比较字符串

比较两个字符串A和B,确定A中是否包含B中所有的字符。字符串A和B中的字符都是 大写字母
您在真实的面试中是否遇到过这个题?
样例

给出 A = "ABCD" B = "ACD",返回 true

给出 A = "ABCD" B = "AABC", 返回 false
注意

在 A 中出现的 B 字符串里的字符不需要连续或者有序。

解题思路

题目换个说法就是,在不管字符顺序的情况下,字符串B是否为A的子集.
想到上一节中写的countChars可以用来对字符串中字符进行计数,就能达到忽略字符次序的效果,直接引用过来

  • 对字符串进行计数得到计数dir
  • 遍历B的计数dir与A中的记录进行对比
    • 遍历dir可以使用Python内置的items()函数
  • 无论是A中没有对应记录还是对应记录小于B 都返回False否则返回True

参考答案

class Solution:
    """
    @param A : A string includes Upper Case letters
    @param B : A string includes Upper Case letters
    @return :  if string A contains all of the characters in B return True else return False
    """

    def compareStrings(self, A, B):
        # write your code here
        countA = self.countChars(A)
        countB = self.countChars(B)
        for key, value in countB.items():
            try:
                if value > countA[key]:
                    return False
            except KeyError:
                return False
        return True

    def countChars(self, stringToCount):
        result = []
        for item in range(ord("z") - ord("A")+1):
            result.append(0)
        for item in stringToCount:
            result[ord(item) - ord("A")] += 1
        return str(result)

相关文章

  • LintCode_chapter1_section2_compa

    容易比较字符串 比较两个字符串A和B,确定A中是否包含B中所有的字符。字符串A和B中的字符都是 大写字母您在真实的...

网友评论

      本文标题:LintCode_chapter1_section2_compa

      本文链接:https://www.haomeiwen.com/subject/brcchttx.html