📜  将字符串的字符重新排序为有效的英文数字表示

📅  最后修改于: 2021-09-06 11:31:19             🧑  作者: Mango

给定一个长度为N的字符串S 由包含重新排序的英文数字[0 – 9]表示的小写字符组成任务是按升序打印这些数字。

例子:

朴素的方法:最简单的方法是生成给定字符串的所有排列,对于每个排列,检查是否可以找到由字符串表示的有效数字。如果发现为真,则按升序打印数字集。

时间复杂度: O(N * N!)
辅助空间: O(1)

有效的方法:这个想法是基于观察到一些字符只出现在一个数字中。

请按照以下步骤解决问题:

  • 初始化一个空字符串ans来存储所需的结果。
  • 将字符串的每个字符的频率存储在M 中
  • 创建一个唯一字符到其对应字符串的映射。
  • 遍历地图,并执行以下步骤:
    • 将与数字对应的唯一字符存储在变量x 中
    • 获取xM 中的出现,并将其存储在变量freq 中
    • 将相应的数字,频率次数附加到ans
    • 遍历与x对应的单词,并在M中将其字符的频率减少freq
  • 打印字符串, ans作为结果。  

下面是上述方法的实现:

Java
// Java program to implement the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to construct the original set of digits
// from the string in ascending order
static String construct_digits(String s)
{
     
    // Store the unique characters
    // corresponding to word and number
    char[] k = { 'z', 'w', 'u', 'x', 'g',
                 'h', 'o', 'f', 'v', 'i' };
 
    String[] l = { "zero", "two", "four", "six", "eight",
                   "three", "one", "five", "seven", "nine" };
 
    int[] c = { 0, 2, 4, 6, 8, 3, 1, 5, 7, 9 };
 
    // Store the required result
    List ans = new ArrayList<>();
 
    // Store the frequency of
    // each character of S
    HashMap d = new HashMap<>();
    for(int i = 0; i < s.length(); i++)
    {
        d.put(s.charAt(i),
              d.getOrDefault(s.charAt(i), 0) + 1);
    }
 
    // Traverse the unique characters
    for(int i = 0; i < k.length; i++)
    {
         
        // Store the count of k[i] in S
        int x = 0;
        if (d.containsKey(k[i]))
            x = d.get(k[i]);
 
        // Traverse the corresponding word
        for(int j = 0; j < l[i].length(); j++)
        {
             
            // Decrement the frequency
            // of characters by x
            if (d.containsKey(l[i].charAt(j)))
                d.put(l[i].charAt(j),
                d.get(l[i].charAt(j)) - x);
        }
 
        // Append the digit x times to ans
        for(int j = 0; j < x; j++)
            ans.add(c[i]);
    }
 
    // Sort the digits in ascending order
    Collections.sort(ans);
    String str = "";
    for(int val : ans)
        str += val;
 
    return str;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given string, s
    String s = "fviefuro";
 
    // Function Call
    System.out.println(construct_digits(s));
}
}
 
// This code is contributed by Kingash


Python3
# Python program to implement the above approach
from collections import Counter
 
# Function to construct the original set of digits
# from the string in ascending order
def construct_digits(s):
   
    # Store the unique characters
    # corresponding to word and number
    k = ["z", "w", "u", "x", "g",
         "h", "o", "f", "v", "i"]
 
    l = ["zero", "two", "four", "six", "eight",
         "three", "one", "five", "seven", "nine"]
 
    c = [0, 2, 4, 6, 8, 3, 1, 5, 7, 9]
     
    # Store the required result
    ans = []
     
    # Store the frequency of
    # each character of S
    d = Counter(s)
 
    # Traverse the unique characters
    for i in range(len(k)):
 
        # Store the count of k[i] in S
        x = d.get(k[i], 0)
         
        # Traverse the corresponding word
        for j in range(len(l[i])):
               
            # Decrement the frequency
            # of characters by x
            d[l[i][j]]-= x
             
        # Append the digit x times to ans
        ans.append(str(c[i])*x)
 
    # Sort the digits in ascending order
    ans.sort()
 
    return "".join(ans)
 
# Driver Code
 
# Given string, s
s = "fviefuro"
 
# Function Call
print(construct_digits(s))


C#
// C# program to implement the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to construct the original set of digits
// from the string in ascending order
static string construct_digits(string s)
{
     
    // Store the unique characters
    // corresponding to word and number
    char[] k = { 'z', 'w', 'u', 'x', 'g',
                 'h', 'o', 'f', 'v', 'i' };
 
    string[] l = { "zero", "two", "four", "six", "eight",
                   "three", "one", "five", "seven", "nine" };
 
    int[] c = { 0, 2, 4, 6, 8, 3, 1, 5, 7, 9 };
 
    // Store the required result
    List ans = new List();
 
    // Store the frequency of
    // each character of S
    Dictionary d = new Dictionary();
    for(int i = 0; i < s.Length; i++)
    {
        if (!d.ContainsKey(s[i]))
            d[s[i]] = 0;
             
        d[s[i]] += 1;
    }
 
    // Traverse the unique characters
    for(int i = 0; i < k.Length; i++)
    {
         
        // Store the count of k[i] in S
        int x = 0;
        if (d.ContainsKey(k[i]))
            x = d[k[i]];
 
        // Traverse the corresponding word
        for(int j = 0; j < l[i].Length; j++)
        {
             
            // Decrement the frequency
            // of characters by x
            if (d.ContainsKey(l[i][j]))
                d[l[i][j]] -= x;
        }
         
        // Append the digit x times to ans
        ans.Add(((c[i]) * x).ToString());
    }
     
    // Sort the digits in ascending order
    ans.Sort();
 
    string str = (String.Join("", ans.ToArray()));
    return str.Replace("0", "");
}
 
// Driver Code
public static void Main(string[] args)
{
     
    // Given string, s
    string s = "fviefuro";
 
    // Function Call
    Console.WriteLine(construct_digits(s));
}
}
 
// This code is contributed by ukasp


输出:
45

时间复杂度: O(N*log(N))
辅助空间: O(N)

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