Suppose we have two sentences s and t. We have to check whether they are similar or not. Here sentence has only English letters. Two sentences are said to be similar when it is possible to add an arbitrary sentence (possibly empty) inside one of these given sentences such that the two sentences become equal.
So, if the input is like s = "we live at city Kolkata" t = "city Kolkata", then the output will be True because we can get s from t by adding sentence "we live in".
To solve this, we will follow these steps −
s1 := a list of words in s
s2 := a list of words in t
if size of s1 > size of s2, then
swap s1 and s2
while s1 is not empty, do
if s2[0] is same as s1[0], then
delete first word from s2
delete first word from s1
otherwise when last word of s2 is same as last word of s1, then
delete last word from s2
delete last word from s1
otherwise,
return false
return true
Example
Let us see the following implementation to get better understanding −
def solve(s, t): s1 = s.split() s2 = t.split() if len(s1) > len(s2): s1,s2 = s2,s1 while(s1): if(s2[0]==s1[0]): s2.pop(0) s1.pop(0) elif(s2[-1]==s1[-1]): s2.pop() s1.pop() else: return(False) return(True) s = "we live at city Kolkata" t = "city Kolkata" print(solve(s, t))
Input
"we live at city Kolkata", "city Kolkata"
Output
True