
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String Can Become Empty by Recursively Deleting a Given Substring in Python
Suppose we have two strings s and t. We can delete t from s any number of times. And t appears only once at a time. We have to check whether s can become empty by removing t as many times as required.
So, if the input is like s = "pipipinnn" t = "pin", then the output will be True as we can remove "pin" from "pipipinnn", then we will get "pipinn", again remove "pin" to get string "pin", then remove it to make it empty.
To solve this, we will follow these steps −
- while size of s > 0, do
- position := starting index of t in s
- if position is not in the s, then
- come out from the loop
- s := remove t from s one time
- return true when size of s is same as 0 otherwise false
Let us see the following implementation to get better understanding −
Example
def solve(s, t): while len(s) > 0: position = s.find(t) if position == -1: break s = s.replace(t, "", 1) return len(s) == 0 s = "pipipinnn" t = "pin" print(solve(s, t))
Input
"pipipinnn", "pin"
Output
True
Advertisements