📌  相关文章
📜  可能由最多 K 个连续相似字符组成的按字典顺序排列的最大字符串

📅  最后修改于: 2021-10-27 07:36:42             🧑  作者: Mango

给定一个字符串S和一个整数K,任务是字典顺序产生最大的字符串可能从给定的字符串,也通过删除字符,即至多K个连续相似字符组成。

例子:

处理方法:按照以下步骤解决问题:

  1. 初始化一个数组charset[]来存储字符串中每个字符的频率。
  2. 遍历字符串并将每个字符的频率存储在数组中。
  3. 初始化一个变量count来存储相似连续字符的计数
  4. 初始化一个字符串newString来存储结果字符串。
  5. 遍历数组charset[]并将(i +’a’)附加到newString
  6. 减少charset[i]并增加count
  7. 检查count = Kcharset[i] > 0 ,然后从charset[] 中找到最近的较小字符并附加到newString 。如果最近的较小字符不可用,则打印newString
  8. 否则,将计数重置为0
  9. 重复步骤 2 到 5 直到charset[i] > 0
  10. 最后,返回newString

下面是上述方法的实现:

C++14
// C++ program for the
// above approach
#include 
using namespace std;
 
// Function to return nearest
// lower character
char nextAvailableChar(vector charset,
                       int start)
{
  // Traverse charset from start-1
  for (int i = start - 1; i >= 0; i--)
  {
    if (charset[i] > 0)
    {
      charset[i]--;
      return char(i + 'a');
    }
  }
  // If no character can be
  // appended
  return '\0';
}
 
// Function to find largest string
string newString(string originalLabel,
                 int limit)
{
  int n = originalLabel.length();
   
  // Stores the frequency of
  // characters
  vector charset(26, 0);
 
  string newStrings = "";
 
  for(char i : originalLabel)
    charset[i - 'a']++;
 
  // Traverse the string
  for (int i = 25; i >= 0; i--)
  {
    int count = 0;
 
    // Append larger character
    while (charset[i] > 0)
    {
      newStrings += char(i + 'a');
 
      // Decrease count in charset
      charset[i]--;
 
      // Increase count
      count++;
 
      // Check if count reached
      // to charLimit
      if (charset[i] > 0 &&
          count == limit)
      {
        // Find nearest lower char
        char next = nextAvailableChar(charset, i);
 
        // If no character can be
        // appended
        if (next == '\0')
          return newStrings;
 
        // Append nearest lower
        // character
        newStrings += next;
 
        // Reset count for next
        // calculation
        count = 0;
      }
    }
  }
 
  // Return new largest string
  return newStrings;
}
 
//Driver code
int main()
{
  //Given string s
  string S = "ccbbb";
   
  int K = 2;
  cout << (newString(S, K));
}
 
// This code is contributed by Mohit Kumar 29


Java
// Java solution for above approach
import java.util.*;
 
class GFG {
 
    // Function to find largest string
    static String newString(String originalLabel,
                            int limit)
    {
        int n = originalLabel.length();
        // Stores the frequency of characters
        int[] charset = new int[26];
 
        // Traverse the string
        for (int i = 0; i < n; i++) {
            charset[originalLabel.charAt(i) - 'a']++;
        }
 
        // Stores the resultant string
        StringBuilder newString
            = new StringBuilder(n);
 
        for (int i = 25; i >= 0; i--) {
 
            int count = 0;
 
            // Append larger character
            while (charset[i] > 0) {
 
                newString.append((char)(i + 'a'));
 
                // Decrease count in charset
                charset[i]--;
 
                // Increase count
                count++;
 
                // Check if count reached to charLimit
                if (charset[i] > 0 && count == limit) {
 
                    // Find nearest lower char
                    Character next
                        = nextAvailableChar(charset, i);
 
                    // If no character can be appended
                    if (next == null)
                        return newString.toString();
 
                    // Append nearest lower character
                    newString.append(next);
 
                    // Reset count for next calculation
                    count = 0;
                }
            }
        }
 
        // Return new largest string
        return newString.toString();
    }
 
    // Function to return nearest lower character
    static Character nextAvailableChar(int[] charset,
                                       int start)
    {
        // Traverse charset from start-1
        for (int i = start - 1; i >= 0; i--) {
 
            if (charset[i] > 0) {
 
                charset[i]--;
                return (char)(i + 'a');
            }
        }
        // If no character can be appended
        return null;
    }
    // Driver Code
    public static void main(String[] args)
    {
        String S = "ccbbb";
        int K = 2;
        System.out.println(newString(S, K));
    }
}


Python3
# Python3 program for the
# above approach
 
# Function to return nearest
# lower character
def nextAvailableChar(charset,
                      start):
 
    # Traverse charset from start-1
    for i in range(start - 1,
                   -1, -1):
        if (charset[i] > 0):
            charset[i] -= 1
            return chr(i + ord('a'))
           
    # If no character can be
    # appended
    return '\0'
 
# Function to find largest
# string
def newString(originalLabel,
              limit):
 
    n = len(originalLabel)
 
    # Stores the frequency of
    # characters
    charset = [0] * (26)
 
    newStrings = ""
 
    for i in originalLabel:
        charset[ord(i) -
                ord('a')] += 1
 
    # Traverse the string
    for i in range(25, -1, -1):
        count = 0
 
        # Append larger character
        while (charset[i] > 0):
            newStrings += chr(i + ord('a'))
 
            # Decrease count in
            # charset
            charset[i] -= 1
 
            # Increase count
            count += 1
 
            # Check if count reached
            # to charLimit
            if (charset[i] > 0 and
                count == limit):
 
                # Find nearest lower char
                next = nextAvailableChar(charset, i)
 
                # If no character can be
                # appended
                if (next == '\0'):
                    return newStrings
 
                # Append nearest lower
                # character
                newStrings += next
 
                # Reset count for next
                # calculation
                count = 0
 
    # Return new largest string
    return newStrings
 
# Driver code
if __name__ == "__main__":
 
    # Given string s
    S = "ccbbb"
 
    K = 2
    print(newString(S, K))
 
# This code is contributed by Chitranayal


C#
// C# solution for above
// approach
using System;
using System.Text;
class GFG{
 
// Function to find largest string
static String newString(String originalLabel,
                        int limit)
{
  int n = originalLabel.Length;
   
  // Stores the frequency of
  // characters
  int[] charset = new int[26];
 
  // Traverse the string
  for (int i = 0; i < n; i++)
  {
    charset[originalLabel[i] - 'a']++;
  }
 
  // Stores the resultant string
  StringBuilder newString =
                new StringBuilder(n);
 
  for (int i = 25; i >= 0; i--)
  {
    int count = 0;
 
    // Append larger character
    while (charset[i] > 0)
    {
      newString.Append((char)(i + 'a'));
 
      // Decrease count in charset
      charset[i]--;
 
      // Increase count
      count++;
 
      // Check if count reached
      // to charLimit
      if (charset[i] > 0 &&
          count == limit)
      {
        // Find nearest lower char
        char next =
             nextAvailableChar(charset, i);
 
        // If no character can be
        // appended
        if (next == 0)
          return newString.ToString();
 
        // Append nearest lower
        // character
        newString.Append(next);
 
        // Reset count for next
        // calculation
        count = 0;
      }
    }
  }
 
  // Return new largest string
  return newString.ToString();
}
 
// Function to return nearest
// lower character
static char nextAvailableChar(int[] charset,
                              int start)
{
  // Traverse charset from start-1
  for (int i = start - 1; i >= 0; i--)
  {
    if (charset[i] > 0)
    {
      charset[i]--;
      return (char)(i + 'a');
    }
  }
   
  // If no character can
  // be appended
  return '\0';
}
 
// Driver Code
public static void Main(String[] args)
{
  String S = "ccbbb";
  int K = 2;
  Console.WriteLine(
          newString(S, K));
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
ccbb

时间复杂度: O(N),其中 N 是给定字符串的长度
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程