📌  相关文章
📜  获得相同字符串所需的最小旋转的 Python3 程序

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

获得相同字符串所需的最小旋转的 Python3 程序

给定一个字符串,我们需要找到获得相同字符串所需的最小旋转次数。

例子:

Input : s = "geeks"
Output : 5

Input : s = "aaaa"
Output : 1

这个想法是基于下面的帖子。

检查字符串是否相互旋转的程序


第 1 步:
初始化结果 = 0(这里的结果是旋转计数)
第 2 步:取一个与原始字符串相等的临时字符串与其自身连接。
第 3 步:现在从第二个字符(或索引 1)开始取大小与原始字符串相同的临时字符串的子字符串。
第 4 步:增加计数。
步骤 5:检查子字符串是否与原始字符串相等。如果是,则打破循环。否则转到第 2 步并从下一个索引开始重复。

Python3
# Python 3 program to determine minimum 
# number of rotations required to yield 
# same string.
  
# Returns count of rotations to get the
# same string back.
def findRotations(str):
      
    # tmp is the concatenated string.
    tmp = str + str
    n = len(str)
  
    for i in range(1, n + 1):
          
        # substring from i index of 
        # original string size.
        substring = tmp[i: i+n]
  
        # if substring matches with 
        # original string then we will 
        # come out of the loop.
        if (str == substring):
            return i
    return n
  
# Driver code
if __name__ == '__main__':
  
    str = "abc"
    print(findRotations(str))
  
# This code is contributed 
# by 29AjayKumar.


Python3
# Python 3 program to determine minimum 
# number of rotations required to yield 
# same string.
   
# input
string = 'aaaa'
check = ''
   
for r in range(1, len(string)+1):
  # checking the input after each rotation
  check = string[r:] + string[:r]
     
  # following if statement checks if input is 
  # equals to check , if yes it will print r and 
  # break out of the loop
  if check == string:
    print(r)
    break
   
# This code is contributed 
# by nagasowmyanarayanan.



输出:
3

时间复杂度: O(n 2 )

Python中的替代实现:

Python3

# Python 3 program to determine minimum 
# number of rotations required to yield 
# same string.
   
# input
string = 'aaaa'
check = ''
   
for r in range(1, len(string)+1):
  # checking the input after each rotation
  check = string[r:] + string[:r]
     
  # following if statement checks if input is 
  # equals to check , if yes it will print r and 
  # break out of the loop
  if check == string:
    print(r)
    break
   
# This code is contributed 
# by nagasowmyanarayanan.


输出:
1

有关更多详细信息,请参阅有关获得相同字符串所需的最小旋转的完整文章!