在 Python 中检查一个字符串的字符是否可以交换以形成另一个字符串

pythonserver side programmingprogramming

假设我们有两个字符串 s 和 t,我们必须检查是否可以通过交换 s 的字符来生成 t。

因此,如果输入为 s = "worldlloeh" t = "helloworld",则输出将为 True,因为我们可以交换 "worldlloeh" 中的字符来创建"helloworld"。

为了解决这个问题,我们将遵循以下步骤 −

  • s_len := s 的大小,t_len := t 的大小
  • 如果 s_len 与 t_len 不同,则
    • 返回 False
  • freq := 一个用于存储 s 中所有字符及其频率的映射
  • 对于范围从 0 到 t_len 的 i,执行
    • freq[t[i]] := freq[t[i]] - 1
    • 如果 freq[t[i]] < 0,则
      • 返回 False
  • 返回 True

让我们看看下面的实现,以便更好地理解 −

示例

from collections import defaultdict
def solve(s, t):
   s_len = len(s)
   t_len = len(t)
   if (s_len != t_len):
      return False
   freq = defaultdict(int)
   for char in s :
      freq[char] += 1
   for i in range(t_len) :
      freq[t[i]] -= 1
      if freq[t[i]] < 0:
         return False
   return True
s = "worldlloeh"
t = "helloworld"
print(solve(s, t))

输入

"worldlloeh", "helloworld"

输出

True

相关文章