📌  相关文章
📜  一次交换中可能出现的字典序最大的字符串

📅  最后修改于: 2021-10-26 06:05:31             🧑  作者: Mango

给定长度为N 的字符串str ,任务是通过最多一次交换获得字典上最大的字符串。

注意:交换字符可能不相邻。

例子:

方法:
为了解决上述问题,其主要思想是使用排序并计算给定字符串最大的辞书字符串可能。在排序从大到小的顺序给定的字符串后,找到指定的字符串的第一个无与伦比的字符和在排序字符串中的字符无法比拟的最后出现取代它。

下面是上述方法的实现:

C++
// C++ implementation to find the
// lexicographically largest string
// by atmost at most one swap
 
#include 
using namespace std;
 
// Function to return the
// lexicographically largest
// string possible by swapping
// at most one character
string findLargest(string s)
{
    int len = s.size();
 
    // Stores last occurrence
    // of every character
    int loccur[26];
 
    // Initialize with -1 for
    // every character
    memset(loccur, -1, sizeof(loccur));
 
    for (int i = len - 1; i >= 0; --i) {
 
        // Keep updating the last
        // occurrence of each character
        int chI = s[i] - 'a';
        // If a previously unvisited
        // character occurs
        if (loccur[chI] == -1) {
            loccur[chI] = i;
        }
    }
    // Stores the sorted string
    string sorted_s = s;
    sort(sorted_s.begin(), sorted_s.end(),
        greater());
 
    for (int i = 0; i < len; ++i) {
        if (s[i] != sorted_s[i]) {
 
            // Character 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
            swap(s[i], s[last_occ]);
            break;
        }
    }
 
    return s;
}
 
// Driver Program
int main()
{
    string s = "yrstvw";
    cout << findLargest(s);
    return 0;
}


Java
// Java implementation to find the
// lexicographically largest string
// by atmost at most one swap
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to return the
// lexicographically largest
// string possible by swapping
// at most one character
static String findLargest(StringBuilder s)
{
    int len = s.length();
     
    // Stores last occurrence
    // of every character
    int[] loccur = new int[26];
     
    // Initialize with -1 for
    // every character
    Arrays.fill(loccur, -1);
     
    for(int i = len - 1; i >= 0; --i)
    {
         
        // Keep updating the last
        // occurrence of each character
        int chI = s.charAt(i) - 'a';
         
        // If a previously unvisited
        // character occurs
        if (loccur[chI] == -1)
        {
            loccur[chI] = i;
        }
    }
     
    // Stores the sorted string
    char[] sorted_s = s.toString().toCharArray();
     
    Arrays.sort(sorted_s);
    reverse(sorted_s);
     
    for(int i = 0; i < len; ++i)
    {
        if (s.charAt(i) != sorted_s[i])
        {
             
            // Character 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 tmp = s.charAt(i);
            s.setCharAt(i, s.charAt(last_occ));
            s.setCharAt(last_occ, tmp);
             
            break;
        }
    }
    return s.toString();
}
 
// Function to reverse array
static void reverse(char a[])
{
    int i, n = a.length;
     
    for(i = 0; i < n / 2; i++)
    {
        char t = a[i];
        a[i] = a[n - i - 1];
        a[n - i - 1] = t;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    StringBuilder s = new StringBuilder("yrstvw");
     
    System.out.println(findLargest(s));
}
}
 
// This code is contributed by offbeat


Python3
# Python3 implementation to find the 
# lexicographically largest string 
# by atmost at most one swap
 
# Function to return the 
# lexicographically largest 
# string possible by swapping 
# at most one character
def findLargest(s):
    Len = len(s)
 
    # Stores last occurrence 
    # of every character
    # Initialize with -1 for 
    # every character
    loccur = [-1 for i in range(26)]
 
    for i in range(Len - 1, -1, -1):
 
        # Keep updating the last 
        # occurrence of each character
        chI = ord(s[i]) - ord('a')
 
        # If a previously unvisited 
        # character occurs
        if(loccur[chI] == -1):
            loccur[chI] = i
     
    # Stores the sorted string
    sorted_s = sorted(s, reverse = True)
    for i in range(Len):
        if(s[i] != sorted_s[i]):
 
            # Character to replace
            chI = (ord(sorted_s[i]) -
                   ord('a'))
 
            # Find the last occurrence 
            # of this character
            last_occ = loccur[chI]
            temp = list(s)
 
            # Swap this with the last 
            # occurrence
            temp[i], temp[last_occ] = (temp[last_occ],
                                       temp[i])
            s = "".join(temp)
            break
    return s
 
# Driver code
s = "yrstvw"
print(findLargest(s))
 
# This code is contributed by avanitrachhadiya2155


C#
// C# implementation to find the
// lexicographically largest string
// by atmost at most one swap
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to return the
// lexicographically largest
// string possible by swapping
// at most one character
static string findLargest(char[] s)
{
    int len = s.Length;
      
    // Stores last occurrence
    // of every character
    int[] loccur = new int[26];
      
    // Initialize with -1 for
    // every character
    Array.Fill(loccur, -1);
      
    for(int i = len - 1; i >= 0; --i)
    {
         
        // Keep updating the last
        // occurrence of each character
        int chI = s[i] - 'a';
          
        // If a previously unvisited
        // character occurs
        if (loccur[chI] == -1)
        {
            loccur[chI] = i;
        }
    }
      
    // Stores the sorted string
    char[] sorted_s = (new string(s)).ToCharArray();
      
    Array.Sort(sorted_s);
    Array.Reverse(sorted_s);
     
    for(int i = 0; i < len; ++i)
    {
        if (s[i] != sorted_s[i])
        {
             
            // Character 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[i];
            s[i] = s[last_occ];
            s[last_occ] = temp;
            break;
        }
    }
    return (new string(s));
}
 
// Driver Code
static void Main()
{
    string str = "yrstvw";
    char[] s = str.ToCharArray();
     
    Console.WriteLine(findLargest(s));
}
}
 
// This code is contributed by divyesh072019


Javascript


输出:
ywstvr