首页 > 解决方案 > 通过使用最多 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 ......我想知道我如何在这个问题中使用上面的问题

标签: c#

解决方案


推荐阅读