📌  相关文章
📜  通过用指定的替换字符替换所有出现的给定字符来修改字符串

📅  最后修改于: 2021-05-17 18:28:52             🧑  作者: Mango

给定由N个小写字母组成的字符串S 以及字符对P [] [2]的数组,任务是通过将所有出现的字符P [i] [0]替换为字符P [i] [1]来修改给定的字符串S。

例子:

天真的方法:解决给定问题的最简单方法是创建原始字符串S的副本,然后对每对(a,b)遍历该字符串,如果找到了字符“ a” ,则将其替换为字符原始字符串副本中的‘b’ 。检查所有对之后,打印修改后的字符串S。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to modify given string
// by replacement of characters
void replaceCharacters(
    string s, vector > p)
{
 
    // Store the length of the string
    // and the number of pairs
    int n = s.size(), k = p.size();
 
    // Create a copy of the string s
    string temp = s;
 
    // Traverse the pairs of characters
    for (int j = 0; j < k; j++) {
 
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Traverse the original string
        for (int i = 0; i < n; i++) {
 
            // If an occurrence of a is found
            if (s[i] == a) {
 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    cout << temp;
}
 
// Driver Code
int main()
{
    string S = "aabbgg";
    vector > P{ { 'a', 'b' },
                             { 'b', 'g' },
                             { 'g', 'a' } };
    replaceCharacters(S, P);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Function to modify given string
// by replacement of characters
static void replaceCharacters(String s, char p[][])
{
     
    // Store the length of the string
    // and the number of pairs
    int n = s.length(), k = p.length;
 
    // Create a copy of the string s
    char temp[] = s.toCharArray();
 
    // Traverse the pairs of characters
    for(int j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Traverse the original string
        for(int i = 0; i < n; i++)
        {
 
            // If an occurrence of a is found
            if (s.charAt(i) == a)
            {
                 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    System.out.println(new String(temp));
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "aabbgg";
    char P[][] = { { 'a', 'b' },
                   { 'b', 'g' },
                   { 'g', 'a' } };
    replaceCharacters(S, P);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Function to modify given string
# by replacement of characters
def replaceCharacters(s, p):
     
    # Store the length of the string
    # and the number of pairs
    n = len(s)
    k = len(p)
 
    # Create a copy of the string s
    temp = s
 
    # Traverse the pairs of characters
    for j in range(k):
         
        # a -> Character to be replaced
        # b -> Replacing character
        a = p[j][0]
        b = p[j][1]
 
        # Traverse the original string
        for i in range(n):
             
            # If an occurrence of a is found
            if (s[i] == a):
                 
                # Replace with b
                temp = list(temp)
                temp[i] = b
                temp = ''.join(temp)
 
    # Print the result
    print(temp)
 
# Driver Code
if __name__ == '__main__':
     
    S = "aabbgg"
    P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ]
           
    replaceCharacters(S, P)
     
# This code is contributed by ipg2016107


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to modify given string
// by replacement of characters
static void replaceCharacters(string s, char[,] p)
{
     
    // Store the length of the string
    // and the number of pairs
    int n = s.Length, k = p.GetLength(0);
 
    // Create a copy of the string s
    char[] temp = s.ToCharArray();
 
    // Traverse the pairs of characters
    for(int j = 0; j < k; j++)
    {
         
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j, 0], b = p[j, 1];
 
        // Traverse the original string
        for(int i = 0; i < n; i++)
        {
 
            // If an occurrence of a is found
            if (s[i] == a)
            {
                 
                // Replace with b
                temp[i] = b;
            }
        }
    }
 
    // Print the result
    Console.WriteLine(new string(temp));
}
 
// Driver Code
public static void Main(string[] args)
{
    string S = "aabbgg";
    char [,]P = { { 'a', 'b' },
                  { 'b', 'g' },
                  { 'g', 'a' } };
                   
    replaceCharacters(S, P);
}
}
 
// This code is contributed by ukasp


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to modify given
// string by replacing characters
void replaceCharacters(
    string s, vector > p)
{
    // Store the size of string
    // and the number of pairs
    int n = s.size(), k = p.size();
 
    // Initialize 2 character arrays
    char arr[26];
    char brr[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for (int i = 0; i < n; i++) {
        arr[s[i] - 'a'] = s[i];
        brr[s[i] - 'a'] = s[i];
    }
 
    // Traverse the array of pairs p
    for (int j = 0; j < k; j++) {
 
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Iterate over the range [0, 25]
        for (int i = 0; i < 26; i++) {
 
            // If it is equal to current
            // character, then replace it
            // in the array b
            if (arr[i] == a) {
                brr[i] = b;
            }
        }
    }
 
    // Print the array brr[]
    for (int i = 0; i < n; i++) {
        cout << brr[s[i] - 'a'];
    }
}
 
// Driver Code
int main()
{
    string S = "aabbgg";
    vector > P{ { 'a', 'b' },
                             { 'b', 'g' },
                             { 'g', 'a' } };
    replaceCharacters(S, P);
 
    return 0;
}


输出:
bbggaa

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

高效方法:可以通过使用大小为26的两个辅助阵列将替换存储在阵列中来优化上述方法。请按照以下步骤解决问题:

  • 初始化大小为26的两个数组arr []brr [] ,并将字符串S的字符存储在两个数组中。
  • 使用变量i遍历对P的数组,并执行以下步骤:
    • 初始化AP [i] [0] ,将B初始化为P [i] [1],表示字符A被字符B替换。
    • 使用变量j[ 0,25 ]范围内迭代,如果arr [j]等于A ,则将brr [j]更新为B。
  • 遍历给定的字符串S,并为每个S [i]将其更新为brr [S [i] –’a’]
  • 完成上述步骤后,打印修改后的字符串S。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to modify given
// string by replacing characters
void replaceCharacters(
    string s, vector > p)
{
    // Store the size of string
    // and the number of pairs
    int n = s.size(), k = p.size();
 
    // Initialize 2 character arrays
    char arr[26];
    char brr[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for (int i = 0; i < n; i++) {
        arr[s[i] - 'a'] = s[i];
        brr[s[i] - 'a'] = s[i];
    }
 
    // Traverse the array of pairs p
    for (int j = 0; j < k; j++) {
 
        // a -> Character to be replaced
        // b -> Replacing character
        char a = p[j][0], b = p[j][1];
 
        // Iterate over the range [0, 25]
        for (int i = 0; i < 26; i++) {
 
            // If it is equal to current
            // character, then replace it
            // in the array b
            if (arr[i] == a) {
                brr[i] = b;
            }
        }
    }
 
    // Print the array brr[]
    for (int i = 0; i < n; i++) {
        cout << brr[s[i] - 'a'];
    }
}
 
// Driver Code
int main()
{
    string S = "aabbgg";
    vector > P{ { 'a', 'b' },
                             { 'b', 'g' },
                             { 'g', 'a' } };
    replaceCharacters(S, P);
 
    return 0;
}
输出:
bbggaa

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