📌  相关文章
📜  Python3 程序查找字典顺序最小的旋转序列设置 2

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

Python3 程序查找字典顺序最小的旋转序列设置 2

编写代码以查找圆形数组中的字典最小值,例如对于数组 BCABDADAB,字典最小值为 ABBCABDAD
输入约束:1 < n < 1000
例子:

Input:  GEEKSQUIZ
Output: EEKSQUIZG

Input:  GFG
Output: FGG

Input :  CAPABCQ
Output : ABCQCAP

我们已经讨论了字典最小字符串旋转中的 O(n 2 Logn) 解决方案 |设置1。这里我们需要找到最小旋转的起始索引,然后打印旋转。

1) Initially assume 0 to be current min 
   starting index.
2) Loop through i = 1 to n-1.
   a) For each i compare sequence starting 
      at i with current min starting index
   b) If sequence starting at i is lexicographically 
      smaller, update current min starting 
      index.

这是算法的伪代码

function findIndexForSmallestSequence(S, n):
    result = 0
    for i = 1:n-1
        if (sequence beginning at i < 
               sequence beginning at result)
            result = i
        end if
    end for
    return result

这是上述算法的实现。

Python 3
# Python 3 program to find lexicographically
# smallest sequence with rotations.
  
# Function to compare lexicographically
# two sequence with different starting
# indexes. It returns true if sequence
# beginning with y is lexicographically
# greater.
import copy
  
  
def printSmallestSequence(s):
    m = copy.copy(s)
    for i in range(len(s) - 1):
  
        if m > s[i:] + s[:i]:
            m = s[i:] + s[:i]
  
    return m
  
#Driver Code
if __name__ == '__main__':
  
    st = 'DCACBCAA'
    print(printSmallestSequence(st))
  
  
# This code is contributed by Koushik Reddy B


输出:

AADCACBC

时间复杂度: O(n^2)
辅助空间: O(1)
请参阅有关按字典顺序排列的最小旋转序列的完整文章 |设置2了解更多详情!