根据字符串的数字部分对字符串进行排序
给定一个大小为N的句子S ,其中每个单词是一个数字部分后跟一堆字符的串联。任务是按数字部分的升序排列单词。
例子:
Input: S = “24-amazing 7-coders 11-are”
Output: coders are amazing
Explanation: order of numeric values are 7, 11, 24.
So they are arranged accordingly
Input: S = “19-Love 10-I 2001-cricket”
Output: I Love cricket
方法:解决方案的方法是基于最小堆的概念。根据空格拆分字符串并将它们放入堆中。最后从堆中弹出它们并按顺序打印它们。这将提供所需的解决方案。
下面是上述方法的实现。
Java
// Java code to implement above approach
import java.util.*;
class GFG {
// For arranging words on the basis
// of numeric part
public static class pair
implements Comparable {
int num;
String word;
pair(int num, String word)
{
this.num = num;
this.word = word;
}
public int compareTo(pair o)
{
return this.num - o.num;
}
}
// Function to arrange the sentence
public static String solve(String str)
{
String[] arr = str.split(" ");
PriorityQueue pq
= new PriorityQueue<>();
for (int i = 0; i < arr.length;
i++) {
String s = arr[i];
String N = "";
int a = 0;
while (s.charAt(a) != '-') {
N += s.charAt(a);
a++;
}
int num = Integer.parseInt(N);
String word = s.substring(a + 1);
pq.add(new pair(num, word));
}
StringBuilder sb
= new StringBuilder();
while (pq.size() > 0) {
pair p = pq.remove();
sb.append(p.word);
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
// Driver code
public static void main(String[] args)
{
String S = "19-Love 10-I 2001-cricket";
String ans = solve(S);
System.out.println(ans);
}
}
Python3
# python3 code for the above approach
# For arranging words on the basis
# of numeric part
# Function to arrange the sentence
def solve(str):
arr = str.split(" ")
pq = []
for i in range(0, len(arr)):
s = arr[i]
N = ""
a = 0
while (s[a] != '-'):
N += s[a]
a += 1
num = int(N)
word = s[a + 1:]
pq.append([num, word])
pq.sort()
sb = ""
k = 0
while (k < len(pq)):
sb += pq[k][1] + " "
k
k += 1
return sb
# Driver code
if __name__ == "__main__":
S = "19-Love 10-I 2001-cricket"
ans = solve(S)
print(ans)
# This code is contributed by rakeshsahni
Javascript
输出
I Love cricket
时间复杂度: O(N)
辅助空间: O(N)