
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if string follows order of characters defined by a pattern or not in Python
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
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
- Related Articles
- Check if a string follows anbn pattern or not in C++
- Check if a string follows a^n b^n pattern or not in Python
- Python Program to check if String contains only Defined Characters using Regex
- Check if the characters of a given string are in alphabetical order in Python
- Check if a string is Isogram or not in Python
- Python - Check if a given string is binary string or not
- Check if any anagram of a string is palindrome or not in Python
- Program to check string is palindrome with lowercase characters or not in Python
- Check whether the vowels in a string are in alphabetical order or not in Python
- Check whether the frequencies of all the characters in a string are prime or not in Python
- Program to check regular expression pattern is matching with string or not in Python
- Python program to check if a string is palindrome or not
- Java program to check order of characters in string
- Python program to check if a given string is Keyword or not
- Check if a doubly linked list of characters is palindrome or not in C++

Advertisements