Check if words in given sentence occur based on the given pattern
Given a pattern ‘pattern‘ and a sentence ‘s‘, the task is to check if the words in the given sentence occur based on the pattern represented in the ‘pattern‘.
Examples:
Input: pattern = “abba”, s = “geeks for for geeks”
Output: true
Explanation: In the pattern, ‘a’ denotes ‘geeks’ and ‘b’ denotes ‘for’. Therefore, sentence ‘s’ follows the pattern ‘pattern’Input: pattern = “abc”, s = “geeks for geeks”
Output: false
Approach: The given problem can be solved by generalizing the pattern formed by words in a given sentence and the characters in the given pattern. Then just check if both the generalized pattern and the given pattern are the same or not. Follow the below steps to solve the problem:
- Create a map to store each word and assign a value to each unique word based on its occurrence.
- Example: for sentence “geeks for for geeks”, the map will be [{“geeks”, 0}, {“for”, 1}]
- Similarly, map the occurrence of each character in the pattern
- Then match the pattern index by index in both maps and print the result
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to check if the words in given // sentence follows the given pattern bool wordPattern(string pattern, string s) { // Stores the occurrence of each word // of a sentence map<string, int > mp; int ch = -1; string temp = "" ; string str = "" , p = "" ; for ( int i = 0; i < s.length(); i++) { if (s[i] == ' ' ) { if (!temp.empty() && mp.find(temp) == mp.end()) { mp.insert({ temp, ++ch }); } if (mp.find(temp) != mp.end()) str += (( char )((mp.find(temp))->second + 'a' )); temp = "" ; } else temp += s[i]; } if (!temp.empty() && mp.find(temp) == mp.end()) mp.insert({ temp, ++ch }); if (mp.find(temp) != mp.end()) str += (( char )((mp.find(temp))->second + 'a' )); map< char , int > m; ch = -1; for ( int i = 0; i < pattern.length(); i++) { if (m.find(pattern[i]) == m.end()) m.insert({ pattern[i], ++ch }); if (m.find(pattern[i]) != m.end()) p += (( char )((m.find(pattern[i]))->second + 'a' )); } return p == str; } // Driver Code int main() { string pattern = "abba" , s = "geeks for for geeks" ; cout << (wordPattern(pattern, s) ? "true" : "false" ); return 0; } |
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to check if the words in given // sentence follows the given pattern static boolean wordPattern(String pattern, String s) { // Stores the occurrence of each word // of a sentence HashMap<String, Integer> mp = new HashMap<>(); int ch = - 1 ; String temp = "" ; String str = "" , p = "" ; for ( int i = 0 ; i < s.length(); i++) { if (s.charAt(i) == ' ' ) { if (!temp.isEmpty() && mp.containsKey(temp)) { mp.put( temp, ++ch ); } if (mp.containsKey(temp)) str += mp.get(temp) + 'a' ; temp = "" ; } else temp += s.charAt(i); } if (!temp.isEmpty() && mp.containsKey(temp) ) mp.put( temp, ++ch ); if (mp.containsKey(temp)) str += mp.get(temp) + 'a' ; HashMap<Character,Integer> m = new HashMap<>(); ch = - 1 ; for ( int i = 0 ; i < pattern.length(); i++) { if (m.containsKey(pattern.charAt(i))) m.put( pattern.charAt(i), ++ch ); if (m.containsKey(pattern.charAt(i))) p +=m.get(pattern.charAt(i)) + 'a' ; } return p == str; } // Driver Code public static void main(String[] args) { String pattern = "abba" , s = "geeks for for geeks" ; System.out.print((wordPattern(pattern, s) ? "true" : "false" )); } } // This code is contributed by Rajput-Ji |
Python3
# Python program for the above approach # Function to check if the words in given # sentence follows the given pattern def wordPattern(pattern, s): # Stores the occurrence of each word # of a sentence mp = {} ch = - 1 temp = "" st = "" p = "" for i in range ( 0 , len (s)): if (s[i] = = ' ' ): if (( len (temp)) and ( not mp.__contains__(temp))): ch + = 1 mp[temp] = ch if (mp.__contains__(temp)): st + = (( chr )((mp[temp]) + 97 )) temp = "" else : temp + = s[i] if (( len (temp)) and ( not mp.__contains__(temp))): ch + = 1 mp[temp] = ch if (mp.__contains__(temp)): st + = (( chr )((mp[temp]) + 97 )) m = {} ch = - 1 for i in range ( 0 , len (pattern)): if ( not m.__contains__(pattern[i])): ch + = 1 m[pattern[i]] = ch if (m.__contains__(pattern[i])): p + = (( chr )(m[pattern[i]] + 97 )) return p = = st # Driver Code pattern = "abba" s = "geeks for for geeks" ans = wordPattern(pattern, s) print ( "true" if ans else "false" ) # This code is contributed by ninja_hattori. |
C#
// C# program for the above approach using System; using System.Collections.Generic; public class GFG { // Function to check if the words in given // sentence follows the given pattern static bool wordPattern(String pattern, String s) { // Stores the occurrence of each word // of a sentence Dictionary<String, int > mp = new Dictionary<String, int >(); int ch = -1; String temp = "" ; String str = "" , p = "" ; for ( int i = 0; i < s.Length; i++) { if (s[i] == ' ' ) { if (temp.Length != 0 && mp.ContainsKey(temp)) { mp.Add(temp, ++ch); } if (mp.ContainsKey(temp)) str += mp[temp] + 'a' ; temp = "" ; } else temp += s[i]; } if (temp.Length != 0 && mp.ContainsKey(temp)) mp.Add(temp, ++ch); if (mp.ContainsKey(temp)) str += mp[temp] + 'a' ; Dictionary< char , int > m = new Dictionary< char , int >(); ch = -1; for ( int i = 0; i < pattern.Length; i++) { if (m.ContainsKey(pattern[i])) m.Add(pattern[i], ++ch); if (m.ContainsKey(pattern[i])) p += m[pattern[i]] + 'a' ; } return p == str; } // Driver Code public static void Main(String[] args) { String pattern = "abba" , s = "geeks for for geeks" ; Console.Write((wordPattern(pattern, s) ? "true" : "false" )); } } // This code is contributed by Rajput-Ji |
Javascript
<script> // JavaScript code for the above approach // Function to check if the words in given // sentence follows the given pattern function wordPattern(pattern, s) { // Stores the occurrence of each word // of a sentence let mp = new Map(); let ch = -1; let temp = "" ; let str = "" ; let p = "" ; for (let i = 0; i < s.length; i++) { if (s[i] == ' ' ) { if (temp.length != 0 && !mp.has(temp)) { ch++; mp.set(temp, ch); } if (mp.has(temp)) str += String.fromCharCode(mp.get(temp) + 'a' .charCodeAt(0)) temp = "" ; } else temp += s[i]; } if (temp.length != 0 && !mp.has(temp)) { ch++; mp.set(temp, ch); } if (mp.has(temp)) str += String.fromCharCode(mp.get(temp) + 'a' .charCodeAt(0)) let m = new Map() ch = -1; for (let i = 0; i < pattern.length; i++) { if (!m.has(pattern[i])) { ch++; m.set((pattern[i], ch)); } if (m.has(pattern[i])) p += String.fromCharCode(m.get(pattern[i]) + 'a' .charCodeAt(0)); } return p != str; } // Driver Code let pattern = "abba" , s = "geeks for for geeks" ; document.write((wordPattern(pattern, s) ? "true" : "false" )); // This code is contributed by Potta Lokesh </script> |
true
Time Complexity: O(NlogN), as we are inserting elements into map and finding values from the map inside the loop.
Auxiliary Space: O(N), as we are using extra space for map.
Please Login to comment...