📌  相关文章
📜  按字符的 ASCII 值总和的升序对字符串数组进行排序

📅  最后修改于: 2021-09-03 13:42:48             🧑  作者: Mango

给定的阵列ARR []N字符串,所述任务是在增加其字符的ASCII值的总和的顺序字符串进行排序。

例子:

的方法:我们的想法是使用辅助阵列为字符串的存储对和它们各自的字符的ASCII值的总和。然后,根据对中的第一个值对数组进行排序,然后打印排序后的字符串。请按照以下步骤解决问题:

  • 初始化成对向量V[]以将字符串的值和字符串本身存储为一对。
  • 使用变量i在范围[0, N – 1] 上迭代:  
    • 找到arr[i]字符的 ASCII 值的总和并将其存储在一个变量中,比如val
    • V 中追加{val, arr[i]}对。
  • 根据对中的第一个值对向量V进行排序。
  • 使用变量i在向量V上在[0, n-1]范围内迭代:  
    • 打印字符串,即v[i].second。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the sum of ASCII
// value of all characters of a string
int getValue(string s)
{
    // Store the required result
    int sum = 0;
 
    // Traverse the string
    for (int i = 0; i < s.size(); i++) {
        sum += s[i];
    }
 
    // Return the sum
    return sum;
}
 
// Function to sort strings in increasing
// order of sum of their ASCII values
void sortStrings(string arr[], int n)
{
 
    // Store pairs of strings and
    // sum of their ASCII values
    vector > v;
 
    // Traverse the array, arr[]
    for (int i = 0; i < n; i++) {
 
        // Find the value of the string
        int val = getValue(arr[i]);
 
        // Append pair {val, arr[i]}
        v.push_back({ val, arr[i] });
    }
 
    // Sort the vector, V in increasing
    // order of the first value of pair
    sort(v.begin(), v.end());
 
    // Print the sorted strings
    for (int i = 0; i < n; i++) {
        cout << v[i].second << " ";
    }
}
 
// Driver Code
int main()
{
 
    // Given Input
    string arr[] = { "geeks", "for", "app", "best" };
    int n = 4;
 
    // Function Call
    sortStrings(arr, n);
 
    return 0;
}


Python3
# Python3 program for the above approach
 
# Function to find the sum of ASCII
# value of all characters of a string
def getValue(s):
     
    # Store the required result
    sum = 0
 
    # Traverse the string
    for i in range(len(s)):
        sum += ord(s[i])
 
    # Return the sum
    return sum
 
# Function to sort strings in increasing
# order of sum of their ASCII values
def sortStrings(arr, n):
 
    # Store pairs of strings and
    # sum of their ASCII values
    v = []
 
    # Traverse the array, arr[]
    for i in range(n):
         
        # Find the value of the string
        val = getValue(arr[i])
 
        # Append pair {val, arr[i]}
        v.append([val, arr[i]])
 
    # Sort the vector, V in increasing
    # order of the first value of pair
    v = sorted(v)
 
    # Print the sorted strings
    for i in range(n):
        print(v[i][1], end = " ")
 
# Driver Code
if __name__ == '__main__':
 
    # Given Input
    arr = [ "geeks", "for", "app", "best" ]
    n = 4
 
    # Function Call
    sortStrings(arr, n)
 
# This code is contributed by mohit kumar 29


输出:
app for best geeks

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

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