美文网首页
LintCode_chapter1_section1_two-s

LintCode_chapter1_section1_two-s

作者: 穆弋 | 来源:发表于2015-11-05 15:43 被阅读57次

    容易
    两个字符串是变位词
    写出一个函数anagram(s, t) 去判断两个字符串是否是颠倒字母顺序构成的
    样例
    输入 s="abcd" t="dcab"
    输出 true

    解题思路

    判断题目给出的两个字符串是否是anagrams,即两个字符串的字母只是次序打乱.

    • 先对两个字符串中字符进行计数
    • 可以遍历字符串对字符计数
    • 可以将计数数据保存成dir格式
      • 需要注意的是计数的时候对第一次出现的字符的处理,我采用的是异常处理,也可以使用if-else语句
    • 再对计数后的数据进行比较
    • Python可以直接使用==进行dir是否相等的判断

    some text
    [some text](javascript:alert('xss'))
    <button>asdasdasd</button>

    参考答案

    class Solution:
        """
        @param s: The first string
        @param b: The second string
        @return true or false
        """
    
        def anagram(self, s, t):
            # write your code here
            countFirst = self.countChars(s)
            countSecond = self.countChars(t)
            return countFirst == countSecond
    
        #
        def countChars(self, stringToCount):
            result = {}
            for item in stringToCount:
                try:
                    result[item] += 1
                except KeyError:
                    result[item] = 1
            return result

    相关文章

      网友评论

          本文标题:LintCode_chapter1_section1_two-s

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