📌  相关文章
📜  根据每个字符串中存在的整数对给定句子进行排序

📅  最后修改于: 2022-05-13 01:56:08.166000             🧑  作者: Mango

根据每个字符串中存在的整数对给定句子进行排序

给定一个作为字符串列表的混杂句子,任务是根据每个字符串中是否存在单个整数来打印排序后的字符串句子。如果两个字符串具有相同的整数,则按字典顺序对它们进行排序。

例子:

方法:这个问题可以用贪心算法来解决我们将创建一个对列表,对的第一个值将保存字符串的整数部分,对的第二个值将按原样保存字符串,然后我们将按升序对这个对列表进行排序,以便具有较低值的字符串整数将在列表中较早。请按照以下步骤解决问题:

  • 创建一个配对列表,比如A ,配对中的第一个值将是字符串中的整数,第二个值将是字符串。
  • 按升序对 A 进行排序
  • 遍历每一对A并打印 pair 的第二个值
C++
// C++ program for above approach
#include 
using namespace std;
 
void sortJumbledList(string jumbled[], int size)
{
   
    // Initializing a list to store pairs
    multimap ans;
   
    // Iterating over JumbledList
    for (int i = 0; i < size; i++) {
        string temp = jumbled[i];
       
       // Finding integer part
        int number = 0;
        for (int j = 0; j < temp.size(); j++) {
            if (temp[j] >= '0' && temp[j] <= '9') {
                number *= 10;
                number += (temp[j] - '0');
            }
        }
       
        // Appending pairs
        ans.insert(pair(number, jumbled[i]));
    }
   
   // Printing sorted word of the string.
    for (auto i : ans) {
        cout << i.second << " ";
    }
}
 
// Driver code
int main()
{
    string JumbledList[] = { "2a",        "grea3t",
                             "l3earning", "geeksfor0geeks",
                             "p5latform", "is1" };
   
   
    sortJumbledList(JumbledList, 6);
    return 0;
}
 
// This code is contributed by maddler.


Python3
# Python program for above approach
def SortJumbledList(JumbledList):
     
    # Initializing a list to store pairs
    A = []
     
    # Iterating over JumbledList
    for string in JumbledList:
       
        # Finding integer part
        integer = []
        for j in string:
            if j in {'0', '1', '2', '3', \
                         '4', '5', '6', \
                         '7', '8', '9'}:
                integer.append(j)
        integer = ''.join(integer)
         
        # Appending pairs
        A.append((integer, string))
         
    # Sorting the list of pairs   
    A.sort()
     
    # Printing sorted word of the string.
    for integer, string in A:
        print(string, end =' ')
         
# Driver Code
JumbledList = [ "2a", "grea3t", \
                "l3earning", \
                "geeksfor0geeks", \
                "p5latform", "is1" ]
 
# Function Call
SortJumbledList(JumbledList)


输出
geeksfor0geeks is1 2a grea3t l3earning p5latform 

时间复杂度: O(N*M),其中 N 是 JumbledList 的长度,M 是字符串的长度。
辅助空间: O(N*M)