Eliminar la primera y la última ocurrencia de un carácter dado de una string

Dado un carácter C y una string S , la tarea es eliminar la primera y la última ocurrencia del carácter C de la string S.

Ejemplos:

Entrada: S = “GeekforGeeks”, C = ‘e’ 
Salida: GeksforGeks 
Explicación: 
G e ekforGe e ks -> GekforGeks

Entrada: S = “holaMundo”, C = ‘l’ 
Salida: heloPalabra

Enfoque: 
La idea es atravesar la string dada desde ambos extremos y encontrar la primera ocurrencia del carácter C encontrado y eliminar las ocurrencias correspondientes. Finalmente, imprima la string resultante.
A continuación se muestra la implementación del enfoque anterior:

C++

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove first and last
// occurrence of a given character
// from the given string
string removeOcc(string& s, char ch)
{
    // Traverse the given string from
    // the beginning
    for (int i = 0; s[i]; i++) {
 
        // If ch is found
        if (s[i] == ch) {
            s.erase(s.begin() + i);
            break;
        }
    }
 
    // Traverse the given string from
    // the end
    for (int i = s.length() - 1;
        i > -1; i--) {
 
        // If ch is found
        if (s[i] == ch) {
            s.erase(s.begin() + i);
            break;
        }
    }
 
    return s;
}
 
// Driver Code
int main()
{
    string s = "hello world";
 
    char ch = 'l';
 
    cout << removeOcc(s, ch);
    return 0;
}

Java

// Java Program to implement
// the above approach
class GFG{
 
// Function to remove first and last
// occurrence of a given character
// from the given String
static String removeOcc(String s, char ch)
{
    // Traverse the given String from
    // the beginning
    for (int i = 0; i < s.length(); i++)
    {
 
        // If ch is found
        if (s.charAt(i) == ch)
        {
            s = s.substring(0, i) +
                s.substring(i + 1);
            break;
        }
    }
 
    // Traverse the given String from
    // the end
    for (int i = s.length() - 1; i > -1; i--)
    {
 
        // If ch is found
        if (s.charAt(i) == ch)
        {
            s = s.substring(0, i) +
                s.substring(i + 1);
            break;
        }
    }
    return s;
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "hello world";
 
    char ch = 'l';
 
    System.out.print(removeOcc(s, ch));
}
}
 
// This code is contributed by sapnasingh4991

Python3

# Python3 program to implement
# the above approach
 
# Function to remove first and last
# occurrence of a given character
# from the given string
def removeOcc(s, ch):
     
    # Traverse the given string from
    # the beginning
    for i in range(len(s)):
 
        # If ch is found
        if (s[i] == ch):
            s = s[0 : i] + s[i + 1:]
            break
     
    # Traverse the given string from
    # the end
    for i in range(len(s) - 1, -1, -1):
 
        # If ch is found
        if (s[i] == ch):
            s = s[0 : i] + s[i + 1:]
            break
 
    return s
 
# Driver Code
s = "hello world"
 
ch = 'l'
 
print(removeOcc(s, ch))
 
# This code is contributed by sanjoy_62

C#

// C# Program to implement
// the above approach
using System;
class GFG{
 
// Function to remove first and last
// occurrence of a given character
// from the given String
static String removeOcc(String s, char ch)
{
    // Traverse the given String from
    // the beginning
    for (int i = 0; i < s.Length; i++)
    {
 
        // If ch is found
        if (s[i] == ch)
        {
            s = s.Substring(0, i) +
                s.Substring(i + 1);
            break;
        }
    }
 
    // Traverse the given String from
    // the end
    for (int i = s.Length - 1; i > -1; i--)
    {
 
        // If ch is found
        if (s[i] == ch)
        {
            s = s.Substring(0, i) +
                s.Substring(i + 1);
            break;
        }
    }
    return s;
}
 
// Driver Code
public static void Main(String[] args)
{
    String s = "hello world";
 
    char ch = 'l';
 
    Console.Write(removeOcc(s, ch));
}
}
 
// This code is contributed by sapnasingh4991

Javascript

<script>
      // JavaScript Program to implement
      // the above approach
      // Function to remove first and last
      // occurrence of a given character
      // from the given String
      function removeOcc(s, ch) {
        // Traverse the given String from
        // the beginning
        for (var i = 0; i < s.length; i++) {
          // If ch is found
          if (s[i] === ch) {
            s = s.substring(0, i) + s.substring(i + 1);
            break;
          }
        }
 
        // Traverse the given String from
        // the end
        for (var i = s.length - 1; i > -1; i--) {
          // If ch is found
          if (s[i] === ch) {
            s = s.substring(0, i) + s.substring(i + 1);
            break;
          }
        }
        return s;
      }
 
      // Driver Code
      var s = "hello world";
      var ch = "l";
 
      document.write(removeOcc(s, ch));
</script>
Producción: 

helo word

Complejidad temporal: O(N)  
Espacio auxiliar: O(1)
 

Método n.º 2: uso del método de índice

  • Convierta la string en una lista.
  • Recorra la lista y, si encontramos un carácter dado, elimine ese índice usando pop()  y rompa el ciclo
  • Recorra la lista desde el final y si encontramos un carácter dado, elimine ese índice usando pop() y rompa el bucle.
  • Únete a la lista e imprímela.

A continuación se muestra la implementación:

Python3

# Python3 program to implement
# the above approach
 
# Function to remove first and last
# occurrence of a given character
# from the given string
 
 
def removeOcc(str, ch):
    # Convert string to list
    s = list(str)
    # Traverse the string from starting position
    for i in range(len(s)):
        # if we find ch then remove it and break the loop
        if(s[i] == ch):
            s.pop(i)
            break
    # Traverse the string from the end
    for i in range(len(s)-1, -1, -1):
        # if we find ch then remove it and break the loop
        if(s[i] == ch):
            s.pop(i)
            break
    # Join the list
    return ''.join(s)
 
 
# Driver Code
s = "hello world"
 
ch = 'l'
 
print(removeOcc(s, ch))
 
# This code is contributed by vikkycirus

Javascript

<script>
 
// JavaScript program to implement
// the above approach
 
// Function to remove first and last
// occurrence of a given character
// from the given string
function removeOcc(str, ch)
{
 
    // Convert string to list
    s = str.split('')
     
    // Traverse the string from starting position
    for(let i = 0; i < s.length; i++)
    {
     
        // if we find ch then remove it and break the loop
        if(s[i] == ch){
            s.splice(i, 1)
            break
        }
    }
     
    // Traverse the string from the end
    for(let i = s.length - 1; i >= 0; i--)
    {
     
        // if we find ch then remove it and break the loop
        if(s[i] == ch)
        {
            s.splice(i, 1)
            break
        }
    }
     
    // Join the list
    return s.join('')
}
 
// Driver Code
let s = "hello world"
let ch = 'l'
document.write(removeOcc(s, ch))
 
// This code is contributed by shinjanpatra
</script>

Complejidad de tiempo: O(N) 

Espacio Auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por rimjhim_25 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *