📌  相关文章
📜  Python3程序检查一个字符串是否可以通过最多X个循环顺时针移位从另一个字符串形成

📅  最后修改于: 2022-05-13 01:54:55.947000             🧑  作者: Mango

Python3程序检查一个字符串是否可以通过最多X个循环顺时针移位从另一个字符串形成

给定一个整数X和两个字符串S1S2 ,任务是通过将字符顺时针循环移动最多 X 次来检查字符串S1是否可以转换为字符串S2

方法:想法是遍历字符串和对于每个索引,并找到两个字符串各自索引处字符的ASCII值之间的差异。如果差值小于 0,则对于循环移位,加 26 以获得实际差值。如果对于任何索引,差异超过X ,则S2不能从S1形成,否则可能。
下面是上述方法的实现:

Python3
# Python3 implementation to check
# that the given string can be
# converted to another string 
# by circular clockwise shift
  
# Function to check that the 
# string s1 can be converted
# to s2 by clockwise circular
# shift of all characters of 
# str1 atmost X times
def isConversionPossible(s1, s2, x):
    n = len(s1)
    s1 = list(s1)
    s2 = list(s2)
      
    for i in range(n):
          
        # Difference between the 
        # ASCII numbers of characters
        diff = ord(s2[i]) - ord(s1[i])
          
        # If both characters 
        # are the same
        if diff == 0:
            continue
          
        # Condition to check if the 
        # difference less than 0 then
        # find the circular shift by 
        # adding 26 to it
        if diff < 0:
            diff = diff + 26
        # If difference between 
        # their ASCII values
        # exceeds X
        if diff > x:
            return False
      
    return True
      
  
# Driver Code
if __name__ == "__main__":
    s1 = "you"
    s2 = "ara"
    x = 6
      
    # Function Call
    result = isConversionPossible(s1, s2, x)
      
    if result:
        print("YES")
    else:
        print("NO")


输出:
YES

时间复杂度: O(N),N=Length(S1)

辅助空间: O(1)

有关详细信息,请参阅关于检查一个字符串是否可以通过最多 X 个圆形顺时针移位从另一个字符串形成的完整文章!