📜  重新排列数字的数字以删除另一个给定数字的任何子序列

📅  最后修改于: 2021-10-26 06:48:30             🧑  作者: Mango

给定两个数字字符串NK (K ≤ N),其中K 的数字按非递减顺序排列,任务是重新排列N 的数字,使得K不会作为N 中的子序列出现。如果无法获得这样的排列,则打印“-1” 。否则打印N 的任何此类有效排列。

例子:

朴素方法:最简单的方法是生成N的每个排列并检查每个排列,如果K出现在其中的子序列。如果发现任何排列为假,则打印该排列。
时间复杂度: O(N*N!)
辅助空间: O(1)

有效方法:上述方法可以基于观察到K的数字按非递减顺序进行优化。因此,通过排序以降序重新排列N的数字。请按照以下步骤解决问题:

  • NK的数字频率分别存储在 HashMap M1M2 中
  • 使用变量(例如i )迭代范围[0, 9]以检查K是否有比N 中出现次数更多的数字。如果M2[i] > M1[i] ,则打印N并返回。
  • 同样,使用变量i迭代范围[0, 9]以检查K是否仅包含 1 个不同的数字。如果M2[i]length(K)相同,则打印“-1”并返回。  
  • 对于所有其他情况,按降序对N进行排序,然后打印N

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find a permutation of
// number N such that the number K does
// not appear as a subsequence in N
void findArrangement(string n, string k)
{
 
    // Stores frequency of digits of N
    unordered_map um1;
    for (int i = 0; i < n.size(); i++) {
        um1[n[i]]++;
    }
 
    // Stores frequency of digits of K
    unordered_map um2;
    for (int i = 0; i < k.size(); i++) {
        um2[k[i]]++;
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++) {
        char ch = '0' + i;
 
        // If true, print N and return
        if (um2[ch] > um1[ch]) {
            cout << n;
            return;
        }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++) {
        char ch = '0' + i;
 
        // If true, print -1 and return
        if (um2[ch] == k.size()) {
            cout << -1;
            return;
        }
    }
 
    // For all other cases, sort N
    // in decreasing order
    sort(n.begin(), n.end(),
         greater());
 
    // Print the value of N
    cout << n;
}
 
// Driver Code
int main()
{
    string N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find a permutation of
// number N such that the number K does
// not appear as a subsequence in N
static void findArrangement(String n, String k)
{
 
    // Stores frequency of digits of N
    HashMap um1 = new HashMap();
    for (int i = 0; i < n.length(); i++)
    {
         if(um1.containsKey(n.charAt(i)))
         {
                um1.put(n.charAt(i), um1.get(n.charAt(i))+1);
            }
            else
            {
                um1.put(n.charAt(i), 1);
            }
    }
 
    // Stores frequency of digits of K
    HashMap um2 = new HashMap();
    for (int i = 0; i < k.length(); i++) {
         if(um2.containsKey(k.charAt(i))){
                um2.put(k.charAt(i), um2.get(k.charAt(i))+1);
            }
            else{
                um2.put(k.charAt(i), 1);
            }
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++)
    {
        char ch = (char) ('0' + i);
 
        // If true, print N and return
        if (um2.containsKey(ch) && um1.containsKey(ch)
                && um2.get(ch) > um1.get(ch))
        {
            System.out.print(n);
            return;
        }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++)
    {
        char ch = (char) ('0' + i);
 
        // If true, print -1 and return
        if (um2.containsKey(ch) && um2.get(ch) == k.length())
        {
            System.out.print(-1);
            return;
        }
    }
 
    // For all other cases, sort N
    // in decreasing order
    n = sortString(n);
 
    // Print the value of N
    System.out.print(n);
}
static String sortString(String inputString)
{
   
    // convert input string to char array
    char tempArray[] = inputString.toCharArray();
 
    // sort tempArray
    Arrays.sort(tempArray);
   
    // return new sorted string
    return new String(new StringBuffer(new String(tempArray)).reverse());
}
   
// Driver Code
public static void main(String[] args)
{
    String N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find a permutation of
# number N such that the number K does
# not appear as a subsequence in N
def findArrangement(n, k) :
 
    # Stores frequency of digits of N
    um1 = dict.fromkeys(n, 0);
     
    for i in range(len(n)):
        um1[n[i]] += 1;
 
    # Stores frequency of digits of K
    um2 = dict.fromkeys(k, 0);
     
    for i in range(len(k)) :
        um2[k[i]] += 1;
 
    # Check if any digit in K has
    # more occurrences than in N
    for i in range(10) :
        ch = chr(ord('0') + i);
 
        if ch in um2 :
           
            # If true, print N and return
            if (um2[ch] > um1[ch]) :
                print(n, end = "");
                return;
 
    # Check if K contains only a
    # single distinct digit
    for i in range(10) :
        ch = chr(ord('0') + i);
     
        if ch in um2 :
         
            # If true, print -1 and return
            if (um2[ch] == len(k)) :
                print(-1, end = "");
                return;
 
    # For all other cases, sort N
    # in decreasing order
    n = list(n)
    n.sort(reverse = True)
     
    # Print the value of N
    print("".join(n));
 
# Driver Code
if __name__ == "__main__" :
 
    N = "93039373637"; K = "339";
 
    # Function Call
    findArrangement(N, K);
 
    # This code is contributed by AnkThon


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find a permutation of
  // number N such that the number K does
  // not appear as a subsequence in N
  static void findArrangement(string n, string k)
  {
 
    // Stores frequency of digits of N
    Dictionary um1 = new Dictionary();
    for (int i = 0; i < n.Length; i++)
    {
      if(um1.ContainsKey(n[i]))
      {
        um1[n[i]]++;
      }
      else
      {
        um1[n[i]] = 1;
      }
    }
 
    // Stores frequency of digits of K
    Dictionary um2 = new Dictionary();
    for (int i = 0; i < k.Length; i++)
    {
      if(um2.ContainsKey(k[i]))
      {
        um2[k[i]]++;
      }
      else
      {
        um2[k[i]] = 1;
      }
    }
 
    // Check if any digit in K has
    // more occurrences than in N
    for (int i = 0; i <= 9; i++)
    {
      char ch = (char) ('0' + i);
 
      // If true, print N and return
      if (um2.ContainsKey(ch) && um1.ContainsKey(ch)
          && um2[ch] > um1[ch])
      {
        Console.Write(n);
        return;
      }
    }
 
    // Check if K contains only a
    // single distinct digit
    for (int i = 0; i <= 9; i++)
    {
      char ch = (char) ('0' + i);
 
      // If true, print -1 and return
      if (um2.ContainsKey(ch) && um2[ch] == k.Length)
      {
        Console.Write(-1);
        return;
      }
    }
 
    // For all other cases, sort N
    // in decreasing order
    n = sortString(n);
 
    // Print the value of N
    Console.Write(n);
  }
 
  static string sortString(string inputString)
  {
 
    // convert input string to char array
    char[] tempArray = inputString.ToCharArray();
 
    // sort tempArray
    Array.Sort(tempArray);
    Array.Reverse(tempArray);
 
    // return new sorted string
    return new string(tempArray);
  }
 
  // Driver codew
  static void Main()
  {
    string N = "93039373637", K = "339";
 
    // Function Call
    findArrangement(N, K);
  }
}
 
// This code is contributed by divyeshrabadiya07


输出:
99776333330

时间复杂度: O(L*log (L)),其中L是字符串N的大小
辅助空间: O(L)