给定两个字符串S和T,任务是通过从任一字符串的开头一次添加一个字符来合并这两个字符串,以形成结果字符串。结果字符串应该是字典序最大的字符串 可以通过合并字符串S和T 形成。
例子:
Input: S = “dbcbb”, T = “cdbbb”
Output : dcdbcbbbbb
Input : S = “geeks“, T = “forgeeks”
Output : gforgeekseeks
方法:解决问题的最简单的想法是从字典中比其他字符串大的字符串贪婪地选择第一个字符。因此,可以使用贪心算法和递归来解决这个问题。请按照以下步骤解决问题:
- 如果任一字符串长度为0 ,则返回S + T作为答案。
- 如果S在字典上大于T,则返回S[0] + maximumMerge(S.substr(1), T) 。
- 否则,取T的第一个字符并调用递归函数maximumMerge(S, T.substr(1))。
下面是上述方法的实现:
C++
// C++ program for the approach
#include
using namespace std;
// Recursive bfunction for finding
// the lexicographically largest string
string largestMerge(string s1, string s2)
{
// If either of the string length is 0,
// return the other string
if (s1.size() == 0 || s2.size() == 0)
return s1 + s2;
// If s1 is lexicographically
// larger than s2
if (s1 > s2) {
// Take first character of s1
// and call the function
return s1[0] + largestMerge(s1.substr(1), s2);
}
// Take first character of s2
// and recursively call function for
// remaining string
return s2[0] + largestMerge(s1, s2.substr(1));
}
// Driver Code
int main()
{
// Given Input
string s1 = "geeks";
string s2 = "forgeeks";
// Function Call
cout << largestMerge(s1, s2) << endl;
return 0;
}
Python3
# Python program for the above approach
# Recursive function for finding
# the lexicographically largest string
def largestMerge(s1, s2):
# If either of the string length is 0,
# return the other string
if len(s1) == 0 or len(s2) == 0:
return s1+s2
# If s1 is lexicographically
# larger than s2
if(s1 > s2):
# Take first character of s1
# and call the function
return s1[0]+largestMerge(s1[1:], s2)
# Take first character of s2
# and recursively call function for
# remaining string
return s2[0]+largestMerge(s1, s2[1:])
# Driver code
if __name__ == '__main__':
# Given Input
s1 = "geeks"
s2 = "forgeeks"
# Function call
print(largestMerge(s1, s2))
# This code is contributed by MuskanKalra1
C#
// C# program for the approach
using System;
class GFG {
// Recursive bfunction for finding
// the lexicographically largest string
static string largestMerge(string s1, string s2)
{
// If either of the string length is 0,
// return the other string
if (s1.Length == 0 || s2.Length == 0)
return s1 + s2;
// If s1 is lexicographically
// larger than s2
if (string.Compare(s1, s2) == 1) {
// Take first character of s1
// and call the function
return s1[0]
+ largestMerge(s1.Substring(1), s2);
}
// Take first character of s2
// and recursively call function for
// remaining string
return s2[0] + largestMerge(s1, s2.Substring(1));
}
// Driver Code
public static void Main()
{
// Given Input
string s1 = "geeks";
string s2 = "forgeeks";
// Function Call
Console.Write(largestMerge(s1, s2));
}
}
// This code is contributed by ukasp.
输出
gforgeekseeks
时间复杂度: O(M×N),其中M和N分别是字符串s1和s2的长度。
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。