美文网首页
《金典》面试题 01.02. 判定是否互为字符重排

《金典》面试题 01.02. 判定是否互为字符重排

作者: 念善 | 来源:发表于2024-06-08 19:57 被阅读0次

题意

给定两个由小写字母组成的字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例 1:

输入: s1 = "abc", s2 = "bca"
输出: true
示例 2:

输入: s1 = "abc", s2 = "bad"
输出: false
说明:

0 <= len(s1) <= 100
0 <= len(s2) <= 100

题解

from collections import Counter

class Solution:
    def CheckPermutation(self, s1: str, s2: str) -> bool:
        cnter1 = Counter(s1)
        cnter2 = Counter(s2)
        return cnter1 == cnter2

总结

可以通过排序解决,但本题是字符串,序列也有限,也可以通过更快捷的方式求解,在计数方面,Python 的 Counter 是个利器。

相关文章

网友评论

      本文标题:《金典》面试题 01.02. 判定是否互为字符重排

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