# Check if string follows order of characters defined by a pattern or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s and another string t as pattern, we have to check whether characters in s follows the same order as determined by characters present in t. Here we have no duplicate characters in the pattern.

So, if the input is like s = "hello world" t = "hw", then the output will be True.

To solve this, we will follow these steps −

• if size of s < size of t, then
• return False
• for i in range 0 to size of t - 2, do
• x := t[i], y := t[i + 1]
• right := last index of x in s
• left := first index of x in s
• if right is -1 or left is -1 or right > left, then
• return False
• return True

Let us see the following implementation to get better understanding −

## Example Code

Live Demo

def solve(s, t):
if len(s) < len(t) :
return False

for i in range(len(t) - 1):
x = t[i]
y = t[i + 1]

right = s.rindex(x)
left = s.index(y)

if right == -1 or left == -1 or right > left:
return False

return True

s = "hello world"
t = "hw"
print(solve(s, t))

## Input

"hello world", "hw"

## Output

True