📌  相关文章
📜  排序字符串数组移除其频率字符之后排序的每个字符串之后是不是2的功率

📅  最后修改于: 2021-09-02 07:36:38             🧑  作者: Mango

给定一个由N 个字符串组成的数组arr[] ,任务是在修改每个字符串后按升序对数组进行排序,删除所有不是 2 的完美幂的字符,然后按降序对修改后的字符串进行排序。

例子:

方法:给定的问题可以通过使用Hashing来存储每个字符串的所有字符的频率,然后执行给定的操作来解决。请按照以下步骤解决问题:

  • 遍历给定的字符串数组arr[]并对每个字符串执行以下操作:
    • 将每个字符的频率存储在 Map 中。
    • 创建一个空字符串,比如T来存储修改后的字符串。
    • 现在遍历地图并将频率为 2 的幂的字符附加到字符串T
    • 按升序对字符串T进行排序,并将其添加到字符串res[]数组中。
  • 按升序对数组res[]进行排序。
  • 完成上述步骤后,打印数组res[] 中的字符串作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if N is power of
// 2 or not
bool isPowerOfTwo(int n)
{
    // Base Case
    if (n == 0)
        return false;
 
    // Return true if N is power of 2
    return (ceil(log2(n))
            == floor(log2(n)));
}
 
// Function to print array of strings
// in ascending order
void printArray(vector res)
{
    // Sort strings in ascending order
    sort(res.begin(), res.end());
 
    // Print the array
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << " ";
    }
}
 
// Function to sort the strings after
// modifying each string according to
// the given conditions
void sortedStrings(string S[], int N)
{
    // Store the frequency of each
    // characters of the string
    unordered_map freq;
 
    // Stores the required
    // array of strings
    vector res;
 
    // Traverse the array of strings
    for (int i = 0; i < N; i++) {
 
        // Temporary string
        string st = "";
 
        // Stores frequency of each
        // alphabet of the string
        for (int j = 0;
             j < S[i].size(); j++) {
 
            // Update frequency of S[i][j]
            freq[S[i][j]]++;
        }
 
        // Traverse the map freq
        for (auto i : freq) {
 
            // Check if the frequency
            // of i.first is a power of 2
            if (isPowerOfTwo(i.second)) {
 
                // Update string st
                for (int j = 0;
                     j < i.second; j++) {
                    st += i.first;
                }
            }
        }
 
        // Clear the map
        freq.clear();
 
        // Null string
        if (st.size() == 0)
            continue;
 
        // Sort the string in
        // descending order
        sort(st.begin(), st.end(),
             greater());
 
        // Update res
        res.push_back(st);
    }
 
    // Print the array of strings
    printArray(res);
}
 
// Driver Code
int main()
{
    string arr[] = { "aaacbb", "geeks", "aaa" };
    int N = sizeof(arr) / sizeof(arr[0]);
    sortedStrings(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to check if N is power of
// 2 or not
static boolean isPowerOfTwo(int n)
{
     
    // Base Case
    if (n == 0)
        return false;
 
    // Return true if N is power of 2
    return (Math.ceil(Math.log(n) / Math.log(2)) ==
           Math.floor(Math.log(n) / Math.log(2)));
}
 
// Function to print array of strings
// in ascending order
static void printArray(ArrayList res)
{
     
    // Sort strings in ascending order
    Collections.sort(res);
 
    // Print the array
    for(int i = 0; i < res.size(); i++)
    {
        System.out.print(res.get(i) + " ");
    }
}
 
// Function to sort the strings after
// modifying each string according to
// the given conditions
static void sortedStrings(String S[], int N)
{
     
    // Store the frequency of each
    // characters of the string
    HashMap freq = new HashMap<>();
 
    // Stores the required
    // array of strings
    ArrayList res = new ArrayList<>();
 
    // Traverse the array of strings
    for(int i = 0; i < N; i++)
    {
         
        // Temporary string
        String st = "";
 
        // Stores frequency of each
        // alphabet of the string
        for(int j = 0; j < S[i].length(); j++)
        {
             
            // Update frequency of S[i][j]
            freq.put(S[i].charAt(j),
                freq.getOrDefault(S[i].charAt(j), 0) + 1);
        }
 
        // Traverse the map freq
        for(char ch : freq.keySet())
        {
             
            // Check if the frequency
            // of i.first is a power of 2
            if (isPowerOfTwo(freq.get(ch)))
            {
 
                // Update string st
                for(int j = 0; j < freq.get(ch); j++)
                {
                    st += ch;
                }
            }
        }
 
        // Clear the map
        freq.clear();
 
        // Null string
        if (st.length() == 0)
            continue;
 
        // Sort the string in
        // descending order
        char myCharArr[] = st.toCharArray();
        Arrays.sort(myCharArr);
        String ns = "";
         
        for(int j = myCharArr.length - 1; j >= 0; --j)
            ns += myCharArr[j];
 
        // Update res
        res.add(ns);
    }
     
    // Print the array of strings
    printArray(res);
}
 
// Driver Code
public static void main(String[] args)
{
    String arr[] = { "aaacbb", "geeks", "aaa" };
    int N = arr.length;
     
    sortedStrings(arr, N);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
from collections import defaultdict
import math
 
# Function to check if N is power of
# 2 or not
def isPowerOfTwo(n):
 
    # Base Case
    if (n == 0):
        return False
 
    # Return true if N is power of 2
    return (math.ceil(math.log2(n)) ==
            math.floor(math.log2(n)))
 
# Function to print array of strings
# in ascending order
def printArray(res):
 
    # Sort strings in ascending order
    res.sort()
 
    # Print the array
    for i in range(len(res)):
        print(res[i], end = " ")
 
# Function to sort the strings after
# modifying each string according to
# the given conditions
def sortedStrings(S, N):
 
    # Store the frequency of each
    # characters of the string
    freq = defaultdict(int)
 
    # Stores the required
    # array of strings
    res = []
 
    # Traverse the array of strings
    for i in range(N):
 
        # Temporary string
        st = ""
 
        # Stores frequency of each
        # alphabet of the string
        for j in range(len(S[i])):
 
            # Update frequency of S[i][j]
            freq[S[i][j]] += 1
 
        # Traverse the map freq
        for i in freq:
 
            # Check if the frequency
            # of i.first is a power of 2
            if (isPowerOfTwo(freq[i])):
 
                # Update string st
                for j in range(freq[i]):
                    st += i
 
        # Clear the map
        freq.clear()
 
        # Null string
        if (len(st) == 0):
            continue
 
        # Sort the string in
        # descending order
        st = list(st)
        st.sort(reverse=True)
        st = ''.join(st)
 
        # Update res
        res.append(st)
 
    # Print the array of strings
    printArray(res)
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ "aaacbb", "geeks", "aaa" ]
    N = len(arr)
     
    sortedStrings(arr, N)
 
# This code is contributed by ukasp


输出:
cbb skgee

时间复杂度: O(N * log N + M * log M),其中 M 是S[] 中字符串的最大长度
辅助空间: O(N)

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