Python | Check order of character in string using OrderedDict( )
Last Updated :
27 Jul, 2023
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples:
Input:
string = "engineers rock"
pattern = "er";
Output: true
Explanation:
All 'e' in the input string are before all 'r'.
Input:
string = "engineers rock"
pattern = "gsr";
Output: false
Explanation:
There are one 'r' before 's' in the input string.
We have existing solution for this problem, please refer Check if string follows order of characters defined by a pattern or not | Set 1. Here we solve this problem quickly in python using OrderedDict(). Approach is very simple,
- Create an OrderedDict of input string which contains characters of input strings as Key only.
- Now set a pointer at the start of pattern string.
- Now traverse generated OrderedDict and match keys with individual character of pattern string, if key and character matches with each other then increment pointer by 1.
- If pointer of pattern reaches it’s end that means string follows order of characters defined by a pattern otherwise not.
Python3
from collections import OrderedDict
def checkOrder( input , pattern):
dict = OrderedDict.fromkeys( input )
ptrlen = 0
for key,value in dict .items():
if (key = = pattern[ptrlen]):
ptrlen = ptrlen + 1
if (ptrlen = = ( len (pattern))):
return 'true'
return 'false'
if __name__ = = "__main__":
input = 'engineers rock'
pattern = 'er'
print (checkOrder( input ,pattern))
|
Output:
true
Check order of character in string Using two pointers
This Approach checks if the characters in the given pattern appear in the same order in the given string. It uses two pointers to keep track of the positions of the characters being compared. If all the characters in the pattern are found in the same order in the string, the function returns True, otherwise False.
Algorithm
1. Initialize two pointers, one for the string and one for the pattern, both starting at 0.
2. Traverse through the string character by character.
3. If the current character in the string matches the current character in the pattern, increment the pattern pointer.
4. Increment the string pointer after processing each character.
5. If the pattern pointer is equal to the length of the pattern, return True.
6. If the end of the string is reached and the pattern pointer is less than the length of the pattern, return False.
Python3
def check_order(string, pattern):
i, j = 0 , 0
for char in string:
if char = = pattern[j]:
j + = 1
if j = = len (pattern):
return True
i + = 1
return False
string = 'engineers rock'
pattern = 'er'
print (check_order(string, pattern))
|
Time Complexity: O(n), where n is length of string
Space Complexity: O(1)
Please Login to comment...