📌  相关文章
📜  在不使用多余空间的情况下,将所有出现的字符串AB替换为C

📅  最后修改于: 2021-04-29 11:52:40             🧑  作者: Mango

给定一个可能包含一个或多个“ AB”出现的字符串str 。在str。中将所有出现的“ AB”替换为“ C”。


例子:

Input  : str = "helloABworld"
Output : str = "helloCworld"

Input  : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"

一个简单的解决方案是查找所有出现的“ AB”。对于每次出现的情况,请将其替换为C,并将更多的所有字符替换回原位。

C++
// C++ program to replace all occurrences of "AB"
// with "C"
#include 
  
void translate(char* str)
{
    if (str[0] == '')
        return;
  
    // Start traversing from second character
    for (int i=1; str[i] != ''; i++)
    {
        // If previous character is 'A' and
        // current character is 'B"
        if (str[i-1]=='A' && str[i]=='B')
        {
            // Replace previous character with
            // 'C' and move all subsequent
            // characters one position back
            str[i-1] = 'C';
            for (int j=i; str[j]!=''; j++)
                str[j] = str[j+1];
        }
    }
    return;
}
  
// Driver code
int main()
{
    char str[] = "helloABworldABGfG";
    translate(str);
    printf("The modified string is :\n");
    printf("%s", str);
}


Java
// Java program to replace all 
// occurrences of "AB" with "C"
import java.io.*;
  
class GFG {
      
    static void translate(char str[])
    {
        // Start traversing from second character
        for (int i = 1; i < str.length; i++)
        {
            // If previous character is 'A' and
            // current character is 'B"
            if (str[i - 1] == 'A' && str[i] == 'B')
            {
                // Replace previous character with
                // 'C' and move all subsequent
                // characters one position back
                str[i - 1] = 'C';
                int j;
                for (j = i; j < str.length - 1; j++)
                    str[j] = str[j + 1];
                str[j] = ' ';
                  
            }
        }
        return;
    }
      
    // Driver code
    public static void main(String args[])
    {
        String st = "helloABworldABGfG";
        char str[] = st.toCharArray();
        translate(str);
        System.out.println("The modified string is :");
        System.out.println(str);
    }
}
  
  
// This code is contributed by Nikita Tiwari.


Python3
# Python 3 program to replace all 
# occurrences of "AB" with "C"
  
def translate(st) :
      
    # Start traversing from second character
    for i in range(1, len(st)) :
          
        # If previous character is 'A' 
        # and current character is 'B"
        if (st[i - 1] == 'A' and st[i] == 'B') :
              
            # Replace previous character with
            # 'C' and move all subsequent
            # characters one position back
            st[i - 1] = 'C'
              
            for j in range(i, len(st) - 1) :
                st[j] = st[j + 1]
                  
            st[len(st) - 1] = ' '
                  
    return
  
# Driver code
st = list("helloABworldABGfG")
translate(st)
  
print("The modified string is :")
print(''.join(st))
  
# This code is contributed by Nikita Tiwari.


C#
// C# program to replace all 
// occurrences of "AB" with "C"
using System;
  
class GFG {
      
    static void translate(char []str)
    {
          
        // Start traversing from second character
        for (int i = 1; i < str.Length; i++)
        {
            // If previous character is 'A' and
            // current character is 'B"
            if (str[i - 1] == 'A' && str[i] == 'B')
            {
                // Replace previous character with
                // 'C' and move all subsequent
                // characters one position back
                str[i - 1] = 'C';
                int j;
                for (j = i; j < str.Length - 1; j++)
                    str[j] = str[j + 1];
                str[j] = ' ';
                  
            }
        }
        return;
    }
      
    // Driver code
    public static void Main()
    {
        String st = "helloABworldABGfG";
        char []str = st.ToCharArray();
        translate(str);
        Console.WriteLine("The modified string is :");
        Console.Write(str);
    }
}
  
  
// This code is contributed by Nitin Mittal.


PHP


C++
// Efficient C++ program to replace all occurrences
// of "AB" with "C"
#include 
  
void translate(char* str)
{
    int len = strlen(str);
    if (len < 2)
       return;
  
    int i = 0;  // Index in modified string
    int j = 0; // Index in original string
  
    // Traverse string
    while (j < len-1)
    {
        // Replace occurrence of "AB" with "C"
        if (str[j] == 'A' && str[j+1] == 'B')
        {
            // Increment j by 2
            j = j + 2;
            str[i++] = 'C';
            continue;
        }
        str[i++] = str[j++];
    }
  
    if (j == len-1)
      str[i++] = str[j];
  
    // add a null character to terminate string
    str[i] = '';
}
  
// Driver code
int main()
{
    char str[] = "helloABworldABGfG";
    translate(str);
    printf("The modified string is :\n");
    printf("%s", str);
}


Java
// Efficient Java program to replace 
// all occurrences of "AB" with "C"
import java.io.*;
  
class GFG {
      
    static void translate(char str[])
    {
        int len = str.length;
        if (len < 2)
        return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string
        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
        str[i++] = str[j];
      
        // add a null character to terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void main(String args[])
    {
        String st="helloABworldABGfG";
        char str[] = st.toCharArray();
        translate(str);
        System.out.println("The modified string is :");
        System.out.println(str);
    }
}
  
  
// This code is contributed 
// by Nikita Tiwari.


Python3
# Python 3 program to replace all 
# occurrences of "AB" with "C"
  
def translate(st) :
    l = len(st)
      
    if (l < 2) :
        return
  
    i = 0 # Index in modified string
    j = 0 # Index in original string
  
    # Traverse string
    while (j < l - 1) :
          
        # Replace occurrence of "AB" with "C"
        if (st[j] == 'A' and st[j + 1] == 'B') :
              
            # Increment j by 2
            j += 2
            st[i] = 'C'
            i += 1
            continue
          
        st[i] = st[j]
        i += 1
        j += 1
      
  
    if (j == l - 1) :
        st[i] = st[j]
        i += 1
  
    # add a null character to
    # terminate string
    st[i] = ' '
    st[l-1] = ' '
  
# Driver code
st = list("helloABworldABGfG")
translate(st)
  
print("The modified string is :")
print(''.join(st))
  
# This code is contributed by Nikita Tiwari.


C#
// Efficient C# program to replace 
// all occurrences of "AB" with "C"
using System;
  
class GFG {
      
    static void translate(char []str)
    {
        int len = str.Length;
        if (len < 2)
            return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string
        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
              
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
            str[i++] = str[j];
      
        // add a null character to 
        // terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void Main()
    {
        String st="helloABworldABGfG";
        char []str = st.ToCharArray();
        translate(str);
        Console.Write("The modified string is :");
        Console.Write(str);
    }
}
  
// This code is contributed by nitin mittal.


输出 :

The modified string is :
helloCworldCGfG

时间复杂度: O(n 2 )
辅助空间: O(1)

一种有效的解决方案是跟踪两个索引,一个索引用于修改的字符串(以下代码中的i ),另一个用于原始字符串(以下代码中的j )。如果在当前索引j处找到“ AB”,则将j增加2,将i增加1。否则,将两者都增加,并将字符从j复制到i。

以下是上述想法的实现。

C++

// Efficient C++ program to replace all occurrences
// of "AB" with "C"
#include 
  
void translate(char* str)
{
    int len = strlen(str);
    if (len < 2)
       return;
  
    int i = 0;  // Index in modified string
    int j = 0; // Index in original string
  
    // Traverse string
    while (j < len-1)
    {
        // Replace occurrence of "AB" with "C"
        if (str[j] == 'A' && str[j+1] == 'B')
        {
            // Increment j by 2
            j = j + 2;
            str[i++] = 'C';
            continue;
        }
        str[i++] = str[j++];
    }
  
    if (j == len-1)
      str[i++] = str[j];
  
    // add a null character to terminate string
    str[i] = '';
}
  
// Driver code
int main()
{
    char str[] = "helloABworldABGfG";
    translate(str);
    printf("The modified string is :\n");
    printf("%s", str);
}

Java

// Efficient Java program to replace 
// all occurrences of "AB" with "C"
import java.io.*;
  
class GFG {
      
    static void translate(char str[])
    {
        int len = str.length;
        if (len < 2)
        return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string
        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
        str[i++] = str[j];
      
        // add a null character to terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void main(String args[])
    {
        String st="helloABworldABGfG";
        char str[] = st.toCharArray();
        translate(str);
        System.out.println("The modified string is :");
        System.out.println(str);
    }
}
  
  
// This code is contributed 
// by Nikita Tiwari.

Python3

# Python 3 program to replace all 
# occurrences of "AB" with "C"
  
def translate(st) :
    l = len(st)
      
    if (l < 2) :
        return
  
    i = 0 # Index in modified string
    j = 0 # Index in original string
  
    # Traverse string
    while (j < l - 1) :
          
        # Replace occurrence of "AB" with "C"
        if (st[j] == 'A' and st[j + 1] == 'B') :
              
            # Increment j by 2
            j += 2
            st[i] = 'C'
            i += 1
            continue
          
        st[i] = st[j]
        i += 1
        j += 1
      
  
    if (j == l - 1) :
        st[i] = st[j]
        i += 1
  
    # add a null character to
    # terminate string
    st[i] = ' '
    st[l-1] = ' '
  
# Driver code
st = list("helloABworldABGfG")
translate(st)
  
print("The modified string is :")
print(''.join(st))
  
# This code is contributed by Nikita Tiwari.

C#

// Efficient C# program to replace 
// all occurrences of "AB" with "C"
using System;
  
class GFG {
      
    static void translate(char []str)
    {
        int len = str.Length;
        if (len < 2)
            return;
      
        // Index in modified string
        int i = 0;
          
        // Index in original string
        int j = 0; 
      
        // Traverse string
        while (j < len - 1)
        {
              
            // Replace occurrence of "AB" with "C"
            if (str[j] == 'A' && str[j + 1] == 'B')
            {
                // Increment j by 2
                j = j + 2;
                str[i++] = 'C';
                continue;
            }
            str[i++] = str[j++];
        }
      
        if (j == len - 1)
            str[i++] = str[j];
      
        // add a null character to 
        // terminate string
        str[i] = ' ';
        str[len - 1]=' ';
    }
      
    // Driver code
    public static void Main()
    {
        String st="helloABworldABGfG";
        char []str = st.ToCharArray();
        translate(str);
        Console.Write("The modified string is :");
        Console.Write(str);
    }
}
  
// This code is contributed by nitin mittal.

输出:

The modified string is :
helloCworldCGfG

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