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

📅  最后修改于: 2021-04-29 11:27:19             🧑  作者: Mango

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

例子:

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

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

  • NK的数字频率分别存储在HashMaps 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)