给定一个长度为N的字符串S ,由小写字母组成,任务是找到字典上最长的字符串,该字符串可以通过替换给定字符串的最多 K 个字符来获得。
例子:
Input: S = “dbza”, K = 1
Output: zbza
Explanation: Replace S[0] (= ‘d’) with ‘z’ to obtain the lexicographically largest string.
Input: S = “zzzz”, K = 2
Output: zzzz
方法:可以使用贪婪方法解决给定的问题。这个想法是从左至右遍历数组,并以Z替换所有非ž字符。请按照以下步骤解决问题:
- 运行i = 0到字符串长度的循环:
- 如果当前字符不等于z ,并且K不等于0:
- 然后,用z替换当前字符。
- K = K – 1。
- 如果当前字符不等于z ,并且K不等于0:
- 最后,返回修改后的字符串。
下面是上述方法的实现:
C++
// C++ implementation of
// the above approach
#include
using namespace std;
string largestString(string s, int k)
{
// Traverse each element of the string
for (int i = 0; i < s.size(); i++) {
// If the current character
// can be replaced with 'z'
if (s[i] != 'z' && k > 0) {
s[i] = 'z';
k--;
}
}
// Return the modified string
return s;
}
// Driver code
int main()
{
string s = "dbza";
int k = 1;
cout << largestString(s, k) << endl;
return 0;
}
Java
// Java implementation of the above approach
class GFG{
static String largestString(String s, int k)
{
// Traverse each element of the string
for(int i = 0; i < s.length(); i++)
{
// If the current character
// can be replaced with 'z'
if (s.charAt(i) != 'z' && k > 0)
{
s = s.replace(s.charAt(i),'z');
k--;
}
}
// Return the modified string
return s;
}
// Driver code
public static void main(String args[])
{
String s = "dbza";
int k = 1;
System.out.println(largestString(s, k));
}
}
// This code is contributed by SoumikMondal
Python3
# Python3 implementation of
# the above approach
def largestString(s, k):
# Traverse each element of the string
for i in range(len(s)):
# If the current character
# can be replaced with 'z'
if (s[i] != 'z' and k > 0):
s[i] = 'z'
k -= 1
# Return the modified string
return "".join(s)
# Driver code
if __name__ == '__main__':
s = "dbza"
k = 1
print (largestString([i for i in s], k))
# This code is contributed by mohit kumar 29
C#
// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
class GFG{
static string largestString(string s, int k)
{
// Traverse each element of the string
for(int i = 0; i < s.Length; i++)
{
// If the current character
// can be replaced with 'z'
if (s[i] != 'z' && k > 0)
{
s = s.Replace(s[i],'z');
k--;
}
}
// Return the modified string
return s;
}
// Driver code
public static void Main()
{
string s = "dbza";
int k = 1;
Console.Write(largestString(s, k));
}
}
// This code is contributed by SURENDRA_GANGWAR
Javascript
输出:
zbza
时间复杂度: O(N)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。