字符串——4、有效的字母异位词

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

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

示例2:

输入: s = "rat", t = "car"
输出: false

说明:假设字符串只包含小写字母。

思路:采用set,遍历set,比较每个字符出现的次数,若出现不等则返回false,否则返回true。

class Solution:
    def isAnagram(self, s, t):
    	if set(s) == set(t) and len(s) == len(t):
    	    for i in set(s):
    	    	if s.count(i) != t.count(i):
    	    	    return False
    	    return True
    	return False

猜你喜欢

转载自blog.csdn.net/weixin_41605837/article/details/84633134