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

📅  最后修改于: 2021-09-04 12:56:59             🧑  作者: Mango

给定一个由N个小写字母组成的字符串S 和字符对的数组P[][2] ,任务是通过用字符P[i][1]替换所有出现的字符P[i][0]来修改给定的字符串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


Javascript


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;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to modify given
// string by replacing characters
static void replaceCharacters(String s, char[][] p)
{
     
    // Store the size of string
    // and the number of pairs
    int n = s.length(), k = p.length;
 
    // Initialize 2 character arrays
    char[] arr = new char[26];
    char[] brr = new char[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for(int i = 0; i < n; i++)
    {
        arr[s.charAt(i) - 'a'] = s.charAt(i);
        brr[s.charAt(i) - 'a'] = s.charAt(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++)
    {
       System.out.print(brr[s.charAt(i) - 'a']);
    }
}
 
// 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 offbeat


Python3
# Python3 program for the above approach
 
# Function to modify given
# string by replacing characters
def replaceCharacters(s, p):
     
    # Store the size of string
    # and the number of pairs
    n, k = len(s), len(p)
 
    # Initialize 2 character arrays
    arr = [0] * 26
    brr = [0] * 26
 
    # Traverse the string s
    # Update arrays arr[] and brr[]
    for i in range(n):
        arr[ord(s[i]) - ord('a')] = s[i]
        brr[ord(s[i]) - ord('a')] = s[i]
 
    # Traverse the array of pairs p
    for j in range(k):
 
        # a -> Character to be replaced
        # b -> Replacing character
        a, b = p[j][0], p[j][1]
 
        # Iterate over the range [0, 25]
        for i in range(26):
             
            # 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 i in range(n):
        print(brr[ord(s[i]) - ord('a')], end = "")
 
# Driver Code
if __name__ == '__main__':
     
    S = "aabbgg"
    P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ]
           
    replaceCharacters(S, P)
 
# This code is contributed by mohit kumar 29


输出:
bbggaa

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

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

  • 初始化大小为26 的两个数组arr[]brr[] ,并将字符串S的字符存储在两个数组中。
  • 使用变量i遍历P对数组并执行以下步骤:
    • A初始化为P[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;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to modify given
// string by replacing characters
static void replaceCharacters(String s, char[][] p)
{
     
    // Store the size of string
    // and the number of pairs
    int n = s.length(), k = p.length;
 
    // Initialize 2 character arrays
    char[] arr = new char[26];
    char[] brr = new char[26];
 
    // Traverse the string s
    // Update arrays arr[] and brr[]
    for(int i = 0; i < n; i++)
    {
        arr[s.charAt(i) - 'a'] = s.charAt(i);
        brr[s.charAt(i) - 'a'] = s.charAt(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++)
    {
       System.out.print(brr[s.charAt(i) - 'a']);
    }
}
 
// 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 offbeat

蟒蛇3

# Python3 program for the above approach
 
# Function to modify given
# string by replacing characters
def replaceCharacters(s, p):
     
    # Store the size of string
    # and the number of pairs
    n, k = len(s), len(p)
 
    # Initialize 2 character arrays
    arr = [0] * 26
    brr = [0] * 26
 
    # Traverse the string s
    # Update arrays arr[] and brr[]
    for i in range(n):
        arr[ord(s[i]) - ord('a')] = s[i]
        brr[ord(s[i]) - ord('a')] = s[i]
 
    # Traverse the array of pairs p
    for j in range(k):
 
        # a -> Character to be replaced
        # b -> Replacing character
        a, b = p[j][0], p[j][1]
 
        # Iterate over the range [0, 25]
        for i in range(26):
             
            # 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 i in range(n):
        print(brr[ord(s[i]) - ord('a')], end = "")
 
# Driver Code
if __name__ == '__main__':
     
    S = "aabbgg"
    P = [ [ 'a', 'b' ],
          [ 'b', 'g' ],
          [ 'g', 'a' ] ]
           
    replaceCharacters(S, P)
 
# This code is contributed by mohit kumar 29
输出:
bbggaa

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live