📌  相关文章
📜  Python程序找到最小旋转数以获得实际字符串

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

Python程序找到最小旋转数以获得实际字符串

给定两个字符串s1 和 s2。任务是找出给定字符串s1 的最小字符串旋转次数,以获得实际的字符串s2。

例子:

Input : eeksg, geeks
Output: 1 
Explanation: g is rotated left to obtain geeks.

Input : eksge, geeks
Output: 2
Explanation : e and g are left rotated to obtain geeks.

方法:

  • 使用字符串切片来旋转字符串。
  • 对字符串进行右旋str1=str1[1:len(str1)]+str1[0]得到实际的字符串。
  • 对字符串执行左旋转m=m[len(m)-1]+m[:len(m)-1]以获得实际的字符串 。
  • 打印左(x)和右(y)旋转的最小值。

时间复杂度: O(n)

下面是实现:

def findRotations(str1, str2):
      
    # To count left rotations 
    # of string
    x = 0
      
    # To count right rotations
    # of string
    y = 0
    m = str1
      
    while True:
          
        # left rotating the string
        m = m[len(m)-1] + m[:len(m)-1] 
          
        # checking if rotated and 
        # actual string are equal.
        if(m == str2):
            x += 1
            break
              
        else:
            x += 1
            if x > len(str2) :
                break
   
    while True:
          
        # right rotating the string
        str1 = str1[1:len(str1)]+str1[0] 
          
        # checking if rotated and actual
        # string are equal.
        if(str1 == str2):
            y += 1
            break
              
        else:
            y += 1
            if y > len(str2):
                break
                  
    if x < len(str2):
          
        # printing the minimum
        # number of rotations.
        print(min(x,y))
          
    else:
        print("given strings are not of same kind")
          
# Driver code
findRotations('sgeek', 'geeks')
输出:
1