Check if string follows order of characters defined by a pattern or not | Set 3
Last Updated :
20 Mar, 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
All 'e' in the input string are before all 'r'.
Input: string = "engineers rock", pattern = "egr";
Output: false
There are two 'e' after 'g' in the input string.
Input: string = "engineers rock", pattern = "gsr";
Output: false
There are one 'r' before 's' in the input string.
We have discussed two approaches to solve this problem.
Check if string follows order of characters defined by a pattern or not | Set 1
Check if string follows order of characters defined by a pattern or not | Set 2
In this approach we first assign a label (or order) to characters of pattern. The labels are assigned in increasing order.
For example, the pattern "gsr" is labeled as following
"g" => 1
"s" => 2
"r" => 3
It means 'g' will come first, then 's', then 'r'
After assigning labels to pattern characters, we iterate through string characters. While traversing, we keep track of label (or order) of last visited character. If label of current character is less than previous character, we return false. Otherwise we update last label. If all characters follow order, we return true.
Below is the implementation
C++
// C++ program to find if a string follows order
// defined by a given pattern.
#include <bits/stdc++.h>
using namespace std;
const int CHAR_SIZE = 256;
// Returns true if characters of str follow
// order defined by a given ptr.
bool checkPattern(string str, string pat)
{
// Initialize all orders as -1
vector<int> label(CHAR_SIZE, -1);
// Assign an order to pattern characters
// according to their appearance in pattern
int order = 1;
for (int i = 0; i < pat.length() ; i++)
{
// give the pattern characters order
label[pat[i]] = order;
// increment the order
order++;
}
// Now one by check if string characters
// follow above order
int last_order = -1;
for (int i = 0; i < str.length(); i++)
{
if (label[str[i]] != -1)
{
// If order of this character is less
// than order of previous, return false.
if (label[str[i]] < last_order)
return false;
// Update last_order for next iteration
last_order = label[str[i]];
}
}
// return that str followed pat
return true;
}
// Driver code
int main()
{
string str = "engineers rock";
string pattern = "gsr";
cout << boolalpha << checkPattern(str, pattern);
return 0;
}
Java
// Java program to find if a string follows order
// defined by a given pattern.
class GFG
{
static int CHAR_SIZE = 256;
// Returns true if characters of str follow
// order defined by a given ptr.
static boolean checkPattern(String str,
String pat)
{
int[] label = new int[CHAR_SIZE];
// Initialize all orders as -1
for (int i = 0; i < CHAR_SIZE; i++)
label[i] = -1;
// Assign an order to pattern characters
// according to their appearance in pattern
int order = 1;
for (int i = 0; i < pat.length(); i++)
{
// give the pattern characters order
label[pat.charAt(i)] = order;
// increment the order
order++;
}
// Now one by check if string characters
// follow above order
int last_order = -1;
for (int i = 0; i < str.length(); i++)
{
if (label[str.charAt(i)] != -1)
{
// If order of this character is less
// than order of previous, return false.
if (label[str.charAt(i)] < last_order)
return false;
// Update last_order for next iteration
last_order = label[str.charAt(i)];
}
}
// return that str followed pat
return true;
}
// Driver code
public static void main(String[] args)
{
String str = "engineers rock";
String pattern = "gsr";
System.out.println(checkPattern(str, pattern));
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python3 program to find if a string follows
# order defined by a given pattern
CHAR_SIZE = 256
# Returns true if characters of str follow
# order defined by a given ptr.
def checkPattern(Str, pat):
# Initialize all orders as -1
label = [-1] * CHAR_SIZE
# Assign an order to pattern characters
# according to their appearance in pattern
order = 1
for i in range(len(pat)):
# Give the pattern characters order
label[ord(pat[i])] = order
# Increment the order
order += 1
# Now one by one check if string
# characters follow above order
last_order = -1
for i in range(len(Str)):
if (label[ord(Str[i])] != -1):
# If order of this character is less
# than order of previous, return false
if (label[ord(Str[i])] < last_order):
return False
# Update last_order for next iteration
last_order = label[ord(Str[i])]
# return that str followed pat
return True
# Driver Code
if __name__ == '__main__':
Str = "engineers rock"
pattern = "gsr"
print(checkPattern(Str, pattern))
# This code is contributed by himanshu77
C#
// C# program to find if a string follows order
// defined by a given pattern.
using System;
class GFG
{
static int CHAR_SIZE = 256;
// Returns true if characters of str follow
// order defined by a given ptr.
static bool checkPattern(String str,
String pat)
{
int[] label = new int[CHAR_SIZE];
// Initialize all orders as -1
for (int i = 0; i < CHAR_SIZE; i++)
label[i] = -1;
// Assign an order to pattern characters
// according to their appearance in pattern
int order = 1;
for (int i = 0; i < pat.Length; i++)
{
// give the pattern characters order
label[pat[i]] = order;
// increment the order
order++;
}
// Now one by check if string characters
// follow above order
int last_order = -1;
for (int i = 0; i < str.Length; i++)
{
if (label[str[i]] != -1)
{
// If order of this character is less
// than order of previous, return false.
if (label[str[i]] < last_order)
return false;
// Update last_order for next iteration
last_order = label[str[i]];
}
}
// return that str followed pat
return true;
}
// Driver code
public static void Main(String[] args)
{
String str = "engineers rock";
String pattern = "gsr";
Console.WriteLine(checkPattern(str, pattern));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find if a string follows order
// defined by a given pattern.
let CHAR_SIZE = 256;
// Returns true if characters of str follow
// order defined by a given ptr.
function checkPattern(str,pat)
{
let label = new Array(CHAR_SIZE);
// Initialize all orders as -1
for (let i = 0; i < CHAR_SIZE; i++)
label[i] = -1;
// Assign an order to pattern characters
// according to their appearance in pattern
let order = 1;
for (let i = 0; i < pat.length; i++)
{
// give the pattern characters order
label[pat[i].charCodeAt(0)] = order;
// increment the order
order++;
}
// Now one by check if string characters
// follow above order
let last_order = -1;
for (let i = 0; i < str.length; i++)
{
if (label[str[i].charCodeAt(0)] != -1)
{
// If order of this character is less
// than order of previous, return false.
if (label[str[i].charCodeAt(0)] < last_order)
return false;
// Update last_order for next iteration
last_order = label[str[i].charCodeAt(0)];
}
}
// return that str followed pat
return true;
}
// Driver code
let str = "engineers rock";
let pattern = "gsr";
document.write(checkPattern(str, pattern));
// This code is contributed by rag2127
</script>
Time Complexity of this program is O(n) with constant extra space (the array label is of constant size, 256).
Auxiliary Space: O(256).
Similar Reads
Check if string follows order of characters defined by a pattern or not | Set 1
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:
8 min read
Check if string follows order of characters defined by a pattern or not | Set 2
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.Another solution to the same problem is posted here.Examples: Input: string = "enginee
8 min read
Check if a string follows a^nb^n pattern or not
Given string str, return true string follows pattern anbn, i.e., it has a's followed by b's such that the number of a's and b's are same. Examples: Input : str = "aabb" Output : Yes Input : str = "abab" Output : No Input : str = "aabbb" Output : No The idea is to first count a's. If number of a's is
8 min read
Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (long
6 min read
Check if a string can be split into substrings starting with N followed by N characters
Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer. Examples: Input: str = "4g12y6hunter" Output: Yes Explanation: Substrings "4g12y" and "6hunter" sat
5 min read
Check if String formed by first and last X characters of a String is a Palindrome
Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
5 min read
Check if both halves of the string have same set of characters in Python
Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the res
3 min read
Python | Check order of character in string using OrderedDict( )
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: trueExplanation: All
3 min read
Check if a string consists only of special characters
Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print âYesâ. Otherwise, print âNoâ. Examples: Input: str = â@#$&%!~âOutput: YesExplanation: Given string contains only special char
9 min read
Check if both halves of the string have same set of characters
Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the
12 min read