c# - 通过使用最多 P 个点获得字典上可能最小的字符串
问题描述
⦁ 替换和/或重新排列这个给定字符串的字符以获得字典上最小的字符串。为此,您可以多次执行以下两个操作。
⦁ 交换字符串中的任意两个字符。此操作需要 1 分。(任意两个,不必相邻) ⦁ 用任何其他小写英文字母替换字符串中的字符。此操作需要 2 分。
通过使用最多 P 个点来获得字典上可能最小的字符串。
输入: ⦁ 两行输入,第一行包含两个整数 N,P。 ⦁ 第二行包含一个由 N 个字符组成的字符串 S。
输出:获得的字典最小字符串。例如
Sample Input:
3 3
bba
Sample Output:
aab
我试过这个,但它不包含 P 点我不知道该怎么做,你们可以帮我解决这个问题:
namespace Lexicographical
{
class GFG
{
// Function to return the lexicographically
// smallest String that can be formed by
// swapping at most one character.
// The characters might not necessarily
// be adjacent.
static String findSmallest(char[] s)
{
int len = s.Length;
// Store last occurrence of every character
int[] loccur = new int[26];
// Set -1 as default for every character.
for (int i = 0; i < 26; i++)
loccur[i] = -1;
for (int i = len - 1; i >= 0; --i)
{
// char index to fill
// in the last occurrence array
int chI = s[i] - 'a';
if (loccur[chI] == -1)
{
// If this is true then this
// character is being visited
// for the first time from the last
// Thus last occurrence of this
// character is stored in this index
loccur[chI] = i;
}
}
char[] sorted_s = s;
Array.Sort(sorted_s);
for (int i = 0; i < len; ++i)
{
if (s[i] != sorted_s[i])
{
// char to replace
int chI = sorted_s[i] - 'a';
// Find the last occurrence
// of this character.
int last_occ = loccur[chI];
// Swap this with the last occurrence
char temp = s[last_occ];
s[last_occ] = s[i];
s[i] = temp;
break;
}
}
return String.Join("", s);
}
// Driver code
public static void Main(String[] args)
{
String s = "abb";
Console.Write(findSmallest(s.ToCharArray()));
}
}
}
这个的输出是 abb 但它应该是 aab ......我想知道我如何在这个问题中使用上面的问题
解决方案
推荐阅读
- android - Bundletool build-bundle 错误:协议消息结束组标记与预期标记不匹配
- python - 在 Django 中导致错误的有效 (?) JSON 数据必须作为字符串提供给前端,并由 javascript 中的 JSON.parse() 转换 - 为什么?
- python - 如何使用 C API 创建一个简单的 numpy 数组,并进行适当的内存管理?
- c# - IGrouping 避免匿名类型
- image - Flutter:如何压缩网络图像
- java - 创建加权图时,LinkedList 不添加对象元素
- python - RuntimeError:仅支持批量空间目标(3D 张量)但获得的目标维度:2
- flutter - 重置块颤动中的事件和状态
- database - 集合值路径无法解析为有效的关联字段
- c++ - 使用递归从字符串生成连续的子字符串