📌  相关文章
📜  通过替换给定字符串的字符以最小移动形成的字典序最大字符串

📅  最后修改于: 2021-10-27 08:43:27             🧑  作者: Mango

如果给定字符串包括N s小写英文字符,任务是打印字典顺序,仅使用的修改的字符串S到包含第一分钟(N,26)小写字符串需要移动的最小数目获得的最大字符串英文字母表,通过将字符串S 的任何字符替换为任何小写英文字母表一次。

例子:

方法:给定的问题可以通过更换或者是重复或不应该与需要插入字符串,直到字符串不包含所有需要的字符,最大的字符字符串的一部分字符来解决。请按照以下步骤解决问题:

  • 初始化一个哈希图,比如M ,并将字符串S的每个字符的频率存储在M 中
  • 初始化的字符阵列,说V到存储中不存在字符串中的字符。
  • 迭代从‘a’开始的前 min( N, 26) 个字符并将当前字符推送到V,如果它不存在于M 中
  • 初始化一个变量, j指向数组的最后一个元素。
  • 使用变量i遍历给定的字符串S并执行以下步骤:
    • 如果S[i]>V[j],则继续。
    • 如果M[S[i]]>1S[i] ≥ ‘a’+min(N, 26) ,则执行以下操作:
      • 递减M [S [I]] 1,并且更换S [I]V [j]的S中。
      • j的值减少1
    • 如果j小于0,则中断。
  • 初始化两个变量,假设rN-1l0
  • r大于0l小于或等于j 时进行迭代并执行以下步骤:
    • 如果M[S[r]]>1S[r] ≥ ‘a’+min(N, 26) ,则执行以下操作:
      • 递减M [S [R]] 1,并且为V [1] S中替换S [R]。
      • l的值增加1
    • r1。
  • 最后,在完成上述步骤后,打印字符串, S作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print the lexicographically
// the largest string obtained in process
// of obtaining a string containing first
// N lower case english alphabtes
string lexicographicallyMaximum(string S, int N)
{
 
    // Store the frequency of each
    // character
    unordered_map M;
 
    // Traverse the string S
    for (int i = 0; i < N; ++i) {
        M[S[i]]++;
    }
 
    // Stores the characters which are
    // not appearing in S
    vector V;
 
    for (char i = 'a'; i < (char)('a' + min(N, 25)); ++i) {
        if (M[i] == 0) {
            V.push_back(i);
        }
    }
 
    // Stores the index of the largest
    // character in the array V, that
    // need to be repaced
    int j = V.size() - 1;
 
    // Traverse the string, S
    for (int i = 0; i < N; ++i) {
 
        // If frequency of S[i] is greater
        // than 1 or it is outside the range
        if (S[i] >= ('a' + min(N, 25)) || M[S[i]] > 1) {
 
            if (V[j] < S[i])
                continue;
 
            // Decrement its frequency by
            // 1
            M[S[i]]--;
 
            // Update S[i]
            S[i] = V[j];
 
            // Decrement j by 1
            j--;
        }
 
        if (j < 0)
            break;
    }
 
    int l = 0;
    // Traverse the string, S
    for (int i = N - 1; i >= 0; i--) {
        if (l > j)
            break;
 
        if (S[i] >= ('a' + min(N, 25)) || M[S[i]] > 1) {
 
            // Decrement its frequency by
            // 1
            M[S[i]]--;
 
            // Update S[i]
            S[i] = V[l];
 
            // increment l by 1
            l++;
        }
    }
    // Return S
    return S;
}
 
// Driver Code
int main()
{
    // Given Input
    string S = "abccefghh";
    int N = S.length();
 
    // Function Call
    cout << lexicographicallyMaximum(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
public class Main
{
    // Function to print the lexicographically
    // the largest string obtained in process
    // of obtaining a string containing first
    // N lower case english alphabtes
    static String lexicographicallyMaximum(String S, int N)
    {
        // Store the frequency of each
        // character
        HashMap M = new HashMap<>();
      
        // Traverse the string S
        for(int i = 0; i < N; ++i)
        {
            if (M.containsKey(S.charAt(i)))
               M.put(S.charAt(i), M.get(S.charAt(i)) + 1);
            else
                M.put(S.charAt(i), 1);
        }
          
        // Stores the characters which are
        // not appearing in S
        Vector V = new Vector();
      
        for(char i = 'a';
                 i < (char)('a' + Math.min(N, 25)); ++i)
        {
            if (M.containsKey(i) == false)
            {
                V.add(i);
            }
        }
      
        // Stores the index of the largest
        // character in the array V, that
        // need to be repaced
        int j = V.size() - 1;
      
        // Traverse the string, S
        for(int i = 0; i < N; ++i)
        {
              
            // If frequency of S[i] is greater
            // than 1 or it is outside the range
            if (S.charAt(i) >= ('a' + Math.min(N, 25)) ||
               (M.containsKey(S.charAt(i)) &&  M.get(S.charAt(i)) > 1))
            {
                if (V.get(j) < S.charAt(i))
                    continue;
                     
                // Decrement its frequency by
                // 1
                M.put(S.charAt(i), M.get(S.charAt(i)) - 1);
      
                // Update S[i]
                S = S.substring(0, i) + V.get(j) + S.substring(i + 1);
      
                // Decrement j by 1
                j--;
            }
            if (j < 0)
                break;
        }
        int l = 0;
          
        // Traverse the string, S
        for(int i = N - 1; i >= 0; i--)
        {
            if (l > j)
                break;
             
            if (S.charAt(i) >=  ('a' + Math.min(N, 25)) ||
                M.containsKey(S.charAt(i)) && M.get(S.charAt(i)) > 1)
            {
                  
                // Decrement its frequency by
                // 1
                M.put(S.charAt(i), M.get(S.charAt(i)) - 1);
      
                // Update S[i]
                S = S.substring(0, i) + V.get(l) + S.substring(i + 1);
      
                // Increment l by 1
                l++;
            }
        }
          
        // Return S
        return S;
    }
 
    public static void main(String[] args)
    {
       
        // Given Input
        String S = "abccefghh";
        int N = S.length();
      
        // Function Call
        System.out.println(lexicographicallyMaximum(S, N));
    }
}
 
// This code is contributed by mukesh07.


Python3
# Python3 program for the above approach
 
# Function to print the lexicographically
# the largest string obtained in process
# of obtaining a string containing first
# N lower case english alphabtes
def lexicographicallyMaximum(S, N):
      
    # Store the frequency of each
    # character
    M = {}
  
    # Traverse the string S
    for i in range(N):
        if S[i] in M:
           M[S[i]] += 1
        else:
            M[S[i]] = 1
      
    # Stores the characters which are
    # not appearing in S
    V = []
  
    for i in range(ord('a'), ord('a') + min(N, 25)):
        if i not in M:
            V.append(chr(i))
  
    # Stores the index of the largest
    # character in the array V, that
    # need to be repaced
    j = len(V) - 1
  
    # Traverse the string, S
    for i in range(N):
          
        # If frequency of S[i] is greater
        # than 1 or it is outside the range
        if (ord(S[i]) >= (ord('a') + min(N, 25)) or
           (S[i] in M and  M[S[i]] > 1)):
            if (ord(V[j]) < ord(S[i])):
                continue
                 
            # Decrement its frequency by
            # 1
            M[S[i]] -= 1
  
            # Update S[i]
            S = S[0:i] + V[j] + S[(i + 1):]
  
            # Decrement j by 1
            j -= 1
         
        if (j < 0):
            break
     
    l = 0
      
    # Traverse the string, S
    for i in range(N - 1, -1, -1):
        if (l > j):
            break
         
        if (ord(S[i]) >= (ord('a') + min(N, 25)) or
            S[i] in M and M[S[i]] > 1):
              
            # Decrement its frequency by
            # 1
            M[S[i]] -= 1
  
            # Update S[i]
            S = S[0:i] + V[l] + S[(i + 1):]
  
            # Increment l by 1
            l += 1
             
    s = list(S)
    s[len(s) - 1] = 'd'
    S = "".join(s)
     
    # Return S
    return S
 
# Driver code
 
# Given Input
S = "abccefghh"
N = len(S)
 
# Function Call
print(lexicographicallyMaximum(S, N))
 
# This code is contributed by rameshtravel07


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to print the lexicographically
// the largest string obtained in process
// of obtaining a string containing first
// N lower case english alphabtes
static string lexicographicallyMaximum(string S, int N)
{
     
    // Store the frequency of each
    // character
    Dictionary M = new Dictionary();
 
    // Traverse the string S
    for(int i = 0; i < N; ++i)
    {
        if (M.ContainsKey(S[i]))
           M[S[i]]++;
        else
            M.Add(S[i], 1);
    }
     
    // Stores the characters which are
    // not appearing in S
    List V = new List();
 
    for(char i = 'a';
             i < (char)('a' + Math.Min(N, 25)); ++i)
    {
        if (M.ContainsKey(i) == false)
        {
            V.Add(i);
        }
    }
 
    // Stores the index of the largest
    // character in the array V, that
    // need to be repaced
    int j = V.Count - 1;
 
    // Traverse the string, S
    for(int i = 0; i < N; ++i)
    {
         
        // If frequency of S[i] is greater
        // than 1 or it is outside the range
        if (S[i] >= ('a' + Math.Min(N, 25)) ||
           (M.ContainsKey(S[i]) &&  M[S[i]] > 1))
        {
            if (V[j] < S[i])
                continue;
                
            // Decrement its frequency by
            // 1
            M[S[i]]--;
 
            // Update S[i]
            S = S.Substring(0, i) + V[j] +
                S.Substring(i + 1);
 
            // Decrement j by 1
            j--;
        }
        if (j < 0)
            break;
    }
    int l = 0;
     
    // Traverse the string, S
    for(int i = N - 1; i >= 0; i--)
    {
        if (l > j)
            break;
        
        if (S[i] >=  ('a' + Math.Min(N, 25)) ||
            M.ContainsKey(S[i]) && M[S[i]] > 1)
        {
             
            // Decrement its frequency by
            // 1
            M[S[i]]--;
 
            // Update S[i]
            S = S.Substring(0, i) + V[l] +
                S.Substring(i + 1);
 
            // Increment l by 1
            l++;
        }
    }
     
    // Return S
    return S;
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    string S = "abccefghh";
    int N = S.Length;
 
    // Function Call
    Console.Write(lexicographicallyMaximum(S, N));
}
}
 
// This code is contributed by bgangwar59


Javascript


输出
abicefghd

时间复杂度: O(N)
辅助空间: O(N)

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