按字典顺序对给定字符串进行排序后,长度为 M 的第 K 个非重叠子字符串
给定 一个大小为N的字符串str和两个整数M和K (N 可被 M 整除),任务是在对给定字符串按字典顺序排序后找到大小为M的第 K个非重叠子字符串
例子:
Input: str = “hwnriw”, M = 3, K = 1
Output: hin
Explanation: Non overlapping substrings of size 3 after sorting are “hin” “rww”.
So 1st string is “hin” .
Input: str = “xeabcks”, M = 3, K = 1
Output: abc
朴素方法:解决问题的基本思想是对整个字符串进行排序,然后找到从索引(K-1)*M开始的第 K 个非重叠子字符串。
请按照以下步骤解决问题:
- 对整个字符串进行排序。
- 如下所述,获取第 K 个子字符串的起始索引。
- 然后从该索引中获取大小为M的子字符串。
下面是上述方法的实现:
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to get the kth substring
string getKthString(int N, int M, int K,
string str)
{
// Sort the entire string
sort(str.begin(), str.end());
// Get the starting index of the kth
// lexicographically string
int startingIndex = (K - 1) * M;
string kthString = "";
// To track the size of string
int size = 0;
// Run a loop till size is not equal to M
for (int i = startingIndex;
i < N && size < M; i++) {
// Add the current character to the
// resulting string
kthString += str[i];
// Increase the size by 1
size++;
}
// Return the resultant string
return kthString;
}
// Driver Function
int main()
{
int N = 6;
int M = 3;
int K = 1;
string str = "xeabcks";
// Function call
cout << getKthString(N, M, K, str);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to get the kth substring
public static String getKthString(int N, int M, int K,
String str)
{
// Sort the entire string
char tempArray[] = str.toCharArray();
Arrays.sort(tempArray);
str = new String(tempArray);
// Get the starting index of the kth
// lexicographically string
int startingIndex = (K - 1) * M;
String kthString = "";
// To track the size of string
int size = 0;
// Run a loop till size is not equal to M
for (int i = startingIndex; i < N && size < M;
i++) {
// Add the current character to the
// resulting string
kthString += str.charAt(i);
// Increase the size by 1
size++;
}
// Return the resultant string
return kthString;
}
public static void main(String[] args)
{
int N = 6;
int M = 3;
int K = 1;
String str = "xeabcks";
// Function call
System.out.print(getKthString(N, M, K, str));
}
}
// This code is contributed by Rohit Pradhan
hin
时间复杂度: O(N * Log N)
辅助空间: O(1)
高效方法:基于以下思想,可以使用散列和前缀和有效地解决问题:
There are total (K-1)*M characters before the starting character of the Kth substring.
So store the frequency of all the characters. Then iterate from the smallest character present in the string and with the help of prefix sum find the first character of the Kth substring.
这将有助于解决线性时间复杂度的问题。