zoukankan      html  css  js  c++  java
  • leetcode 字谜

    242. Valid Anagram
    Easy

    Given two strings s and , 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

    ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常

    class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
    s_l = len(s)
    t_l = len(t)
    dic = {}
    for i in range(97,123):
    dic[chr(i)] = [0,0]
    if s_l != t_l:
    return False
    for i in s:
    dic[i][0] += 1
    for j in t:
    dic[j][1] += 1
    for j in t:
    if dic[j][0] != dic[j][1]:
    return False
    return True

    最优的方法

    class Solution:
    def isAnagram(self, s: str, t: str) -> bool:

    '''
    s_l = len(s)
    t_l = len(t)
    dic = {}
    for i in range(97,123):
    dic[chr(i)] = [0,0]
    if s_l != t_l:
    return False
    for i in s:
    dic[i][0] += 1
    for j in t:
    dic[j][1] += 1
    for j in t:
    if dic[j][0] != dic[j][1]:
    return False'''
    for i in string.ascii_lowercase:
    if s.count(i) != t.count(i):
    return False
    return True

    return True

  • 相关阅读:
    Qt QPainter::end: Painter ended whith 2 saced states
    2月6日学习内容
    2月5日学习总结
    2月4日所学内容
    2月3日学习内容
    2月2日学习收获
    2月1日学习内容
    构建之法读后感(一)
    11月从小工到专家读后感(二)
    11月从小工到专家的读后感(一)
  • 原文地址:https://www.cnblogs.com/find1/p/10770938.html
Copyright © 2011-2022 走看看