2019-02-02

LeetCode 242. Valid Anagram.jpg

LeetCode 242. Valid Anagram

Description

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.

描述

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

思路

  • 字母异位词是指使用了相同的字母(种类相同,且每个种类使用的次数相等)的单词.
  • 题目给定了只会使用小写字母,我们生命两个长度为26的数组,统计s和t中字母出现的次数,然后判断所有的字母是不是一一对应相等即可.
# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-02 16:55:46
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-02 18:05:09


class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t): return False
        # 题目明确只会给定26个小写字母
        scount, tcount = [0 for _ in range(26)], [0 for _ in range(26)]
        for x, y in zip(s, t):
            # 统计s中字母出现的次数
            scount[ord(x) - ord('a')] += 1
            # 统计t中字母出现的次数
            tcount[ord(y) - ord('a')] += 1
        # 返回s和t中字母出现的次数是否一一对应相等
        return scount == tcount

源代码文件在这里.
©本文首发于何睿的博客,欢迎转载,转载需保留文章来源,作者信息和本声明.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • LeetCode 241. Different Ways to Add Parentheses Descripti...
    ruicore阅读 307评论 0 0
  • LeetCode 238. Product of Array Except Self Description Gi...
    ruicore阅读 175评论 0 0
  • LeetCode 240. Search a 2D Matrix II Description Write an ...
    ruicore阅读 260评论 0 0
  • fathom 单词释义:to understand sth complicated or mysteriousn....
    薄荷巧克力_阅读 252评论 0 0
  • 半年前帮我爸装了一个win10,他的电脑虽然配置比较低,但是跑win10完全没问题。可是这次放假回来他居然跟我说他...
    冫羽灬赫丶阅读 1,312评论 0 2