字符串在Python中转换为另一个字符串

假设我们有两个字符串str1和str2。而且它们的长度相同,我们必须检查是否可以通过执行零次或多次转换将str1转换为str2。

在一次转换中,我们可以将str1中所有出现的一个字符转换为其他任何小写英文字符。我们必须检查是否可以将str1转换为str2。

因此,如果输入类似于str1 =“ aabcc”,str2 =“ ccdee”,则输出为true,因为将'c'转换为'e'然后将'b'转换为'd'然后将'a'转换为'c '。在这里,我们必须记住转换顺序很重要。

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

  • 定义一个功能compress()。这将花费

  • n:= s的大小

  • 一个:=一个新列表

  • 数:= 1

  • 对于1到n范围内的i,执行

    • 数:=数+ 1

    • 在末尾插入计数

    • 计数:= 1

    • 如果s [i]与s [i-1]不同,则

    • 除此以外,

    • 在末尾插入计数

    • 返回一个

    • 定义一个功能canConvert()。这将花费str1,str2

    • 一个:= compress(str1)

    • b:=压缩(str2)

    • n:= a的大小,m:= b的大小

    • d:=新映射

    • n:= n,m的最小值

    • i:= 0

    • 当i <n不为零时,

      • 返回False

      • 如果a [i]> b [i]不为零,则

      • 我:=我+ 1

    • 对于str2中的每个i,

      • d [i]:= 1

      • 如果我不在d中为非零,则

    • 如果26-d的大小不为零或str1与str2相同,则返回True

    让我们看下面的实现以更好地理解-

    示例

    class Solution(object):
       def compress(self,s):
          n = len(s)
          a = []
          count = 1
          for i in range(1,n):
             if s[i]!=s[i-1]:
                a.append(count)
                count=1
             else:
                count+=1
          a.append(count)
          return a
       def canConvert(self, str1, str2):
          a = self.compress(str1)
          b = self.compress(str2)
          n = len(a)
          m = len(b)
          d={}
          n = min(n,m)
          i = 0
          while i<n:
             if a[i]>b[i]:
                return False
                i+=1
             for i in str2:
                if i not in d:
                   d[i]=1
          return True if 26-len(d) or str1 == str2 else False
    
    ob = Solution()print(ob.canConvert("aabcc", "ccdee"))

    输入值

    "aabcc", "ccdee"

    输出结果

    True