- 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 if a string can be formed from another string using given constraints in Python
Suppose we have two strings lowercase strings s and t. We have to check whether t can be generated from s using following constraints or not −
Characters of t is there in s for example if there are two 'a' in t, then s should also have two 'a's.
When any character in t is not in s, check whether the previous two characters (previous two ASCII values) are there in s or not. For example, if 'f' is in t but not in s, then 'd' and 'e' can be used from s to make 'f'.
So, if the input is like s = "pghn" t = "pin", then the output will be True as we can make 'i' from 'g' and 'h' to make "pin".
To solve this, we will follow these steps −
- freq := frequency of each character in s
- for i in range 0 to size of t, do
- if freq[t[i]] is non-zero, then
- freq[t[i]] := freq[t[i]] - 1
- otherwise when freq[first previous character of t[i]] and freq[second previous character of t[i]] is non-zero, then
- decrease freq[first previous character of t[i]] by 1
- decrease freq[second previous character of t[i]] by 1
- otherwise,
- return False
- if freq[t[i]] is non-zero, then
- return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict def solve(s, t): freq = defaultdict(lambda:0) for i in range(0, len(s)): freq[s[i]] += 1 for i in range(0, len(t)): if freq[t[i]]: freq[t[i]] -= 1 elif (freq[chr(ord(t[i]) - 1)] and freq[chr(ord(t[i]) - 2)]): freq[chr(ord(t[i]) - 1)] -= 1 freq[chr(ord(t[i]) - 2)] -= 1 else: return False return True s = "pghn" t = "pin" print(solve(s, t))
Input
"pghn", "pin"
Output
True
Advertisements