📌  相关文章
📜  通过用另一个数组中的元素替换它们的 GCD 对字符串数组进行排序

📅  最后修改于: 2021-09-04 08:04:01             🧑  作者: Mango

给定两个大小分别为NM的字符串arr[]k[]数组,任务是在用arr[i]k[j的 GCD 替换每个数组元素arr[i]后对数组arr[]进行排序],其中0 ≤ i < N0 ≤ j < M。如果无法对数组进行排序,则打印-1

注意:两个字符串AB的 GCD 是最小的字符串,当连接多次时,变为等于AB 。如果不存在这样的字符串,则返回一个空字符串。

例子:

方法:可以贪婪地解决给定的问题。请按照以下步骤解决问题:

  • 初始化一个变量,例如prev = ” (空字符串),以按排序顺序存储前一个字符串。
  • 遍历数组,对于i在范围[0, N – 1]
    • 使用arr[i]k[j] 的每个字符串计算 GCD 对于范围[0, M – 1] 中的j
    • 找到最小的字符串说, optEle字典序大于prev
    • 更新arr[i] = optEle
    • 更新上一个= arr[i]
  • 如果数组按升序排序。打印数组
  • 否则,打印-1。

下面是实现。

Python3
# Python implementation of the 
# above approach
  
# Function to find gcd of two numbers
def GCD(a, b):
    if(b == 0):
        return a
    else:
        return GCD(b, a % b)
  
  
# Function to find GCD of two strings 
def StringGCD(a, b):
      
    # Length of gcd of two strings
    gcd = GCD(len(a), len(b))
      
    if a[:gcd] == b[:gcd]:
        if a*(len(b)//gcd) == b*(len(a)//gcd):
            return a[:gcd]
      
    # GCD of strings does not exist
    return ' '
  
# Function to check if the array is
# sorted in increasing order or not
def isIncreasing(arr):
    
    for i in range(len(arr)-1):
        if arr[i] >= arr[i + 1]:
            return False
            
    return True
  
# Function to check if arr[] can
# be sorted in increasing order
def sortByGcd(arr, k):
    
      # Previous string
    prev = ''
      
    # Iterate through the array
    for i in range(len(arr)):
        
        # Initialize optimal
        # element by arr[i]
        optEle = arr[i]
          
        # Flag to find first
        # string > prev
        flag = True
          
        for idx in range(len(k)):
            
            # Gcd of two strings
            Ele = StringGCD(arr[i], k[idx])
              
            # If Ele > prev and flag is set
            if Ele > prev and flag:
                
                  # Update optEle
                optEle = Ele
                  
                # Update Flag
                flag = False
              
            # If Ele > prev
            if Ele > prev:
                    
                # Update optEle
                optEle = min(optEle, Ele)
                  
        # Update arr[i] by optEle
        arr[i] = optEle
          
        # Update prev by arr[i]
        prev = arr[i]
          
    # Check is arr[] is sorted in ascending order
    if isIncreasing(arr):
        return arr
        
    # Sorted order is not possible
    else:
        return -1
  
  
# Driver Code
  
arr = ['geeks', 'for', 'geeks']
k = ['geeks', 'for']
print(sortByGcd(arr, k))


时间复杂度: O(N * K * log(min(N, K))
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live