- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 whether given string can be generated after concatenating given strings in Python
Suppose we have two strings s and t and r, we have to check whether r = s | t or r = t + s where | denotes concatenation.
So, if the input is like s = "world" t = "hello" r = "helloworld", then the output will be True as "helloworld" (r) = "hello" (t) | "world" (s).
To solve this, we will follow these steps −
- if size of r is not same as the sum of the lengths of s and t, then
- return False
- if r starts with s, then
- if r ends with t, then
- return True
- if r ends with t, then
- if r starts with t, then
- if r ends with s, then
- return True
- if r ends with s, then
- return False
Let us see the following implementation to get better understanding −
Example Code
def solve(s, t, r): if len(r) != len(s) + len(t): return False if r.startswith(s): if r.endswith(t): return True if r.startswith(t): if r.endswith(s): return True return False s = "world" t = "hello" r = "helloworld" print(solve(s, t, r))
Input
"world", "hello", "helloworld"
Output
True
Advertisements