Open In App

Change the given string according to the given conditions

Last Updated : 15 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S, the task is to change the string if it doesn’t follow any of the rules given below and print the updated string. The rules for the proofreading are: 

  1. If there are three consecutive characters, then it’s a wrong spell. Remove one of the characters. For Example string “ooops” can be changed to “oops”.
  2. If two pairs of the same characters (AABB) are connected together, it’s a wrong spell. Delete one of the characters of the second pair. For Example string “hello” can be changed to “hello”.
  3. The rules follow the priority from left to right.

Examples: 

Input: S = “hello”
Output: hello
Explanation:
As per the Rule #2
hello => hello

Input: S = “woooow”
Output: woow
Explanation: 
As per the Rule #2
woooow => wooow
As per the Rule #1
wooow => woow

Approach: The idea is to traverse the string and if there is a wrong spelling, remove the extra characters according to the given conditions. As the priority of errors is from left to right, and according to the rules given, it can be seen that the judgement of spelling errors will not conflict. Consider traversing from left to right, adding the already legal characters to the result. Below are the steps:

  • Initialize a stack to store the characters and to compare the last characters of the string.
  • Traverse the string and add the character to the stack.
  • Check the last 3 characters of the stack, if the same then pop the character at the top of the stack.
  • Check the last 4 characters of the stack, if the same then pop the character at the top of the stack.
  • Finally, return the characters of the stack.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to proofread the spells
string proofreadSpell(string& str)
{
    vector<char> result;
 
    // Loop to iterate over the
    // characters of the string
    for (char c : str) {
 
        // Push the current character c
        // in the stack
        result.push_back(c);
 
        int n = result.size();
 
        // Check for Rule 1
        if (n >= 3) {
            if (result[n - 1]
                    == result[n - 2]
                && result[n - 1]
                       == result[n - 3]) {
                result.pop_back();
            }
        }
        n = result.size();
 
        // Check for Rule 2
        if (n >= 4) {
            if (result[n - 1]
                    == result[n - 2]
                && result[n - 3]
                       == result[n - 4]) {
                result.pop_back();
            }
        }
    }
 
    // To store the resultant string
    string resultStr = "";
 
    // Loop to iterate over the
    // characters of stack
    for (char c : result) {
        resultStr += c;
    }
 
    // Return the resultant string
    return resultStr;
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "hello";
 
    // Function Call
    cout << proofreadSpell(str);
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to proofread the spells
public static String proofreadSpell(String str)
{
    Vector<Character> result = new Vector<Character>();
 
    // Loop to iterate over the
    // characters of the string
    for(int i = 0; i < str.length(); i++)
    {
         
        // Push the current character c
        // in the stack
        result.add(str.charAt(i));
 
        int n = result.size();
 
        // Check for Rule 1
        if (n >= 3)
        {
            if (result.get(n - 1) ==
                result.get(n - 2) &&
                result.get(n - 1) ==
                result.get(n - 3))
            {
                result.remove(result.size() - 1);
            }
        }
        n = result.size();
 
        // Check for Rule 2
        if (n >= 4)
        {
            if (result.get(n - 1) ==
                result.get(n - 2) &&
                result.get(n - 3) ==
                result.get(n - 4))
            {
                result.remove(result.size() - 1);
            }
        }
    }
 
    // To store the resultant string
    String resultStr = "";
 
    // Loop to iterate over the
    // characters of stack
    for(Character c : result)
    {
        resultStr += c;
    }
     
    // Return the resultant string
    return resultStr;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given string str
    String str = "hello";
 
    // Function call
    System.out.println(proofreadSpell(str));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3




# Python3 program for
# the above approach
 
# Function to proofread
# the spells
def proofreadSpell(str):
   
    result = []
 
    # Loop to iterate over the
    # characters of the string
    for c in str:
 
        # Push the current character c
        # in the stack
        result.append(c)
        n = len(result)
 
        # Check for Rule 1
        if(n >= 3):
            if(result[n - 1] == result[n - 2] and
               result[n - 1] == result[n - 3]):
                result.pop()
        n = len(result)
 
        # Check for Rule 2
        if(n >= 4):
            if(result[n - 1] == result[n - 2] and
               result[n - 3] == result[n - 4]):
                result.pop()
 
    # To store the
    # resultant string
    resultStr = ""
 
    # Loop to iterate over the
    # characters of stack
    for c in result:
        resultStr += c
 
    # Return the resultant string
    return resultStr
 
# Driver Code
 
# Given string str
str = "hello"
 
# Function Call
print(proofreadSpell(str))
 
# This code is contributed by avanitrachhadiya2155


C#




// C# program for the above approach 
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
 
// Function to proofread the spells
static string proofreadSpell(string str)
{
     
    // ArrayList result=new ArrayList();
    List<char> result = new List<char>();
     
    // Loop to iterate over the
    // characters of the string
    foreach(char c in str)
    {
 
        // Push the current character c
        // in the stack
        result.Add(c);
 
        int n = result.Count;
 
        // Check for Rule 1
        if (n >= 3)
        {
            if (result[n - 1] == result[n - 2] &&
                result[n - 1] == result[n - 3])
            {
                result.RemoveAt(n - 1);
            }
        }
         
        n = result.Count;
 
        // Check for Rule 2
        if (n >= 4)
        {
            if (result[n - 1] == result[n - 2] &&
                result[n - 3] == result[n - 4])
            {
                result.RemoveAt(n - 1);
            }
        }
    }
 
    // To store the resultant string
    string resultStr = "";
 
    // Loop to iterate over the
    // characters of stack
    foreach(char c in result)
    {
        resultStr += c;
    }
 
    // Return the resultant string
    return resultStr;
}
 
// Driver code
public static void Main(string[] args)
{
     
    // Given string str
    string str = "hello";
 
    // Function call
    Console.Write(proofreadSpell(str));
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to proofread the spells
function proofreadSpell(str)
{
    var result = [];
 
    // Loop to iterate over the
    // characters of the string
    str.split('').forEach(c => {
        
        // Push the current character c
        // in the stack
        result.push(c);
 
        var n = result.length;
 
        // Check for Rule 1
        if (n >= 3) {
            if (result[n - 1]
                    == result[n - 2]
                && result[n - 1]
                       == result[n - 3]) {
                result.pop();
            }
        }
        n = result.length;
 
        // Check for Rule 2
        if (n >= 4) {
            if (result[n - 1]
                    == result[n - 2]
                && result[n - 3]
                       == result[n - 4]) {
                result.pop();
            }
        }
    });
 
    // To store the resultant string
    var resultStr = "";
 
    // Loop to iterate over the
    // characters of stack
    result.forEach(c => {
         
        resultStr += c;
    });
 
    // Return the resultant string
    return resultStr;
}
 
// Driver Code
// Given string str
var str = "hello";
// Function Call
document.write( proofreadSpell(str));
 
 
</script>


Output

hello

Time Complexity: O(N) 
Auxiliary Space: O(N)

Another Approach:

  1. Initialize two pointers i and j to the start of the string.
  2. Traverse the string from left to right using the j pointer:
    a. If the current character at j is the same as the character two positions to the left (i.e., j – 2), skip this character by incrementing j.
    b. If the current character at j is the same as the character one position to the left (i.e., j – 1) and the character two positions to the left is the same as the character three positions to the left (i.e., i – 1), skip the current character by incrementing j.
    c. Otherwise, add the current character to the result string and increment both i and j.
  3. Return the result string.

C++




#include <iostream>
#include <string>
 
using namespace std;
 
string proofreadSpell(string str)
{
    int n = str.size();
    string result = "";
 
    // Initialize two pointers
    int i = 0, j = 0;
 
    while (j < n) {
        // Check for Rule 1
        if (j >= 2 && str[j] == str[j - 1]
            && str[j] == str[j - 2]) {
            j++;
        }
        // Check for Rule 2
        else if (j >= 3 && str[j] == str[j - 1]
                 && str[j - 2] == str[j - 3]) {
            j++;
        }
        else {
            result += str[j];
            i++;
            j++;
        }
    }
 
    return result;
}
 
int main()
{
 
    string str = "hello";
    cout << proofreadSpell(str) << endl;
 
    return 0;
}


Java




public class ProofreadSpell {
    public static String proofreadSpell(String str) {
        int n = str.length();
        StringBuilder result = new StringBuilder();
 
        // Initialize two pointers
        int i = 0, j = 0;
 
        while (j < n) {
            // Check for Rule 1
            if (j >= 2 && str.charAt(j) == str.charAt(j - 1)
                    && str.charAt(j) == str.charAt(j - 2)) {
                j++;
            }
            // Check for Rule 2
            else if (j >= 3 && str.charAt(j) == str.charAt(j - 1)
                    && str.charAt(j - 2) == str.charAt(j - 3)) {
                j++;
            } else {
                result.append(str.charAt(j));
                i++;
                j++;
            }
        }
 
        return result.toString();
    }
 
    public static void main(String[] args) {
        String str = "hello";
        System.out.println(proofreadSpell(str));
    }
}


Python3




def proofread_spell(str):
    n = len(str)
    result = ""
    i, j = 0, 0
 
    while j < n:
        # Check for Rule 1
        if j >= 2 and str[j] == str[j - 1] and str[j] == str[j - 2]:
            j += 1
        # Check for Rule 2
        elif j >= 3 and str[j] == str[j - 1] and str[j - 2] == str[j - 3]:
            j += 1
        else:
            result += str[j]
            i += 1
            j += 1
 
    return result
 
# Driver code
str = "hello"
print(proofread_spell(str))


C#




using System;
 
class Program
{
    // Function to proofread and correct the input string
    static string ProofreadSpell(string str)
    {
        int n = str.Length;
        string result = "";
 
        // Initialize two pointers
        int i = 0, j = 0;
 
        while (j < n)
        {
            // Check for Rule 1: If three consecutive characters are the same, skip one.
            if (j >= 2 && str[j] == str[j - 1] && str[j] == str[j - 2])
            {
                j++;
            }
            // Check for Rule 2: If four consecutive characters form a palindrome, skip one.
            else if (j >= 3 && str[j] == str[j - 1] && str[j - 2] == str[j - 3])
            {
                j++;
            }
            else
            {
                // If the current character does not violate any rules, add it to the result.
                result += str[j];
                i++;
                j++;
            }
        }
 
        return result;
    }
 
    static void Main()
    {
        string str = "hello";
        string correctedStr = ProofreadSpell(str);
 
        // Print the corrected string
        Console.WriteLine(correctedStr);
 
        // Keep the console window open
        Console.ReadLine();
    }
}
 
// This code is contributed by Dwaipayan Bandyopadhyay


Javascript




// Javascript code addition
function proofreadSpell(str) {
  const n = str.length;
  let result = '';
 
  // Initialize two pointers
  let i = 0, j = 0;
 
  while (j < n)
  {
   
    // Check for Rule 1
    if (j >= 2 && str[j] == str.charAt[j - 1] && str[j] == str[j - 2]) {
      j++;
    }
    // Check for Rule 2
    else if (j >= 3 && str[j] == str.charAt[j - 1] && str[j - 2] == str[j - 3]) {
      j++;
    } else {
      result += str[j];
      i++;
      j++;
    }
  }
 
  return result;
}
 
const str = "hello";
console.log(proofreadSpell(str));
 
// the code is contributed by Arushi and Gautam goel.


Output

hello

Time Complexity: O(N)
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads