Remove last occurrence of a word from a given sentence string
Last Updated :
07 Oct, 2023
Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is.
Examples:
Input: S = “This is GeeksForGeeks”, W=”Geeks”
Output: This is GeeksFor
Explanation:
The last occurrence of “Geeks” in the string is substring over the range [16, 20].
Input: S=”Hello World”, W=”Hell”
Output: o World
Explanation:
The last occurrence of “Hell” in the string is substring over the range [0, 3].
Approach: The problem can be solved by iterating over every index i of string S and checking if there is a substring starting from the index i, which is equal to string W. Follow the steps below to solve the problem:
- If N is smaller than M, print S, as there can be no occurrence of W in S.
- Initialize a variable i as N-M to iterate over the string S.
- Iterate until i is greater than 0 and perform the following steps:
- Check whether the substring over the range [i, i+M-1] is equal to string W or not. If it is equal, then remove the substring over the range [i, i+M-1] from string S and then break.
- Otherwise, continue.
- Finally, after completing the above steps, print the string S as the answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string removeLastOccurrence(string S, string W, int N,
int M)
{
if (M > N)
return S;
for ( int i = N - M; i >= 0; i--) {
int flag = 0;
for ( int j = 0; j < M; j++) {
if (S[j + i] != W[j]) {
flag = 1;
break ;
}
}
if (flag == 0) {
for ( int j = i; j < N - M; j++)
S[j] = S[j + M];
S.resize(N - M);
break ;
}
}
return S;
}
int main()
{
string S = "This is GeeksForGeeks" ;
string W = "Geeks" ;
int N = S.length();
int M = W.length();
cout << removeLastOccurrence(S, W, N, M) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static String removeLastOccurrence(String S, String W,
int N, int M)
{
char [] ch = S.toCharArray();
if (M > N)
return S;
for ( int i = N - M; i >= 0 ; i--)
{
int flag = 0 ;
for ( int j = 0 ; j < M; j++)
{
if (ch[j + i] != W.charAt(j))
{
flag = 1 ;
break ;
}
}
if (flag == 0 )
{
for ( int j = i; j < N - M; j++)
ch[j] = ch[j + M];
break ;
}
}
char [] chh = new char [N - M];
for ( int i = 0 ; i < N - M; i++)
{
chh[i] = ch[i];
}
return String.valueOf(chh);
}
public static void main(String[] args)
{
String S = "This is GeeksForGeeks" ;
String W = "Geeks" ;
int N = S.length();
int M = W.length();
System.out.print(removeLastOccurrence(S, W, N, M));
}
}
|
Python3
def removeLastOccurrence(S, W, N, M):
S = [i for i in S]
W = [i for i in W]
if (M > N):
return S
for i in range (N - M, - 1 , - 1 ):
flag = 0
for j in range (M):
if (S[j + i] ! = W[j]):
flag = 1
break
if (flag = = 0 ):
for j in range (i,N - M):
S[j] = S[j + M]
S = S[:N - M]
break
return "".join(S)
if __name__ = = '__main__' :
S = "This is GeeksForGeeks"
W = "Geeks"
N = len (S)
M = len (W)
print (removeLastOccurrence(S, W, N, M))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static string removeLastOccurrence( string S, string W, int N,
int M)
{
char [] ch = S.ToCharArray();
if (M > N)
return S;
for ( int i = N - M; i >= 0; i--)
{
int flag = 0;
for ( int j = 0; j < M; j++) {
if (ch[j + i] != W[j]) {
flag = 1;
break ;
}
}
if (flag == 0) {
for ( int j = i; j < N - M; j++)
ch[j] = ch[j + M];
Array.Resize( ref ch,N - M);
break ;
}
}
S = string .Concat(ch);
return S;
}
public static void Main()
{
string S = "This is GeeksForGeeks" ;
string W = "Geeks" ;
int N = S.Length;
int M = W.Length;
Console.Write(removeLastOccurrence(S, W, N, M));
}
}
|
Javascript
<script>
function removeLastOccurrence(S, W, N, M)
{
if (M > N)
return S;
for (let i = N - M; i >= 0; i--)
{
let flag = 0;
for (let j = 0; j < M; j++) {
if (S[j + i] != W[j]) {
flag = 1;
break ;
}
}
if (flag == 0) {
for (let j = i; j < N - M; j++)
S[j] = S[j + M];
S = S.substring(0,N - M);
break ;
}
}
return S;
}
let S = "This is GeeksForGeeks" ;
let W = "Geeks" ;
let N = S.length;
let M = W.length;
document.write(removeLastOccurrence(S, W, N, M), "</br>" );
</script>
|
Time Complexity: O(M*N)
Auxiliary Space: O(1)
Approach:
To find the position of the last occurrence of W in S, we can use the rfind() function. This function returns the position of the last occurrence of the specified string in the calling string object. If the specified string is not found, the function returns string::npos, which is a constant value representing an invalid position or index.
Once we have the position of the last occurrence of W in S, we can use the erase() function to remove the substring containing W from S. The erase() function takes two arguments – the starting position from where the substring needs to be erased and the length of the substring to be erased.
If the string W is not present in S, the rfind() function will return string::npos, indicating that W is not present in S. In this case, we can simply return S as it is.
- Use the rfind() function to find the position of the last occurrence of string W in string S.
- If the string W is not present in S, return S as it is.
- If W is found in S, remove the substring containing W from S using the erase() function.
- Return the modified string S.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string removeLastOccurrence(string S, string W, int N, int M)
{
int pos = S.rfind(W);
if (pos == string::npos)
return S;
S.erase(pos, M);
return S;
}
int main()
{
string S = "This is GeeksForGeeks" ;
string W = "Geeks" ;
int N = S.length();
int M = W.length();
cout << removeLastOccurrence(S, W, N, M) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static String
removeLastOccurrence(String S, String W, int N, int M)
{
int pos = S.lastIndexOf(W);
if (pos == - 1 )
return S;
StringBuilder sb = new StringBuilder(S);
sb.delete(pos, pos + M);
return sb.toString();
}
public static void main(String[] args)
{
String S = "This is GeeksForGeeks" ;
String W = "Geeks" ;
int N = S.length();
int M = W.length();
System.out.println(
removeLastOccurrence(S, W, N, M));
}
}
|
Python3
def remove_last_occurrence(S, W):
pos = S.rfind(W)
if pos = = - 1 :
return S
S = S[:pos] + S[pos + len (W):]
return S
if __name__ = = "__main__" :
S = "This is GeeksForGeeks"
W = "Geeks"
print (remove_last_occurrence(S, W))
|
C#
using System;
class Program
{
static string RemoveLastOccurrence( string S, string W)
{
int pos = S.LastIndexOf(W);
if (pos == -1)
return S;
S = S.Remove(pos, W.Length);
return S;
}
static void Main()
{
string S = "This is GeeksForGeeks" ;
string W = "Geeks" ;
Console.WriteLine(RemoveLastOccurrence(S, W));
}
}
|
Javascript
function removeLastOccurrence(S, W) {
const pos = S.lastIndexOf(W);
if (pos === -1)
return S;
const sb = S.slice(0, pos) + S.slice(pos + W.length);
return sb;
}
function main() {
const S = "This is GeeksForGeeks" ;
const W = "Geeks" ;
console.log(removeLastOccurrence(S, W));
}
main();
|
Time Complexity: O(N), where N is the length of string S.
Space Complexity: O(1), as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...