
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Word Pattern in C++
Suppose we have a pattern and a string str, find if str follows the same pattern. Here follow means there is a bijection between a letter in pattern and a non-empty word in str.
So, if the input is like pattern = "cbbc", str = "word pattern pattern word", then the output will be True.
To solve this, we will follow these steps −
strcin := str
Define an array of words
for each word in strcin
insert word at the end of words
Define one map p2i
i := 0
pat := empty string
for c in pattern −
if c is not member of p2i, then −
(increase i by 1)
p2i[c] := i
pat := pat concatenate p2i[c]
Define one map str2i
i := 0
pat1 := blank string
for c in words −
if c is not member of str2i, then −
(increase i by 1)
str2i[c] := i
pat1 := pat1 concatenate str2i[c]
return true when pat1 is same as pat
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool wordPattern( string pattern, string str ) { istringstream strcin(str); string word; vector<string> words; while (strcin >> word) words.push_back(word); unordered_map<char, int> p2i; int i = 0; string pat = ""; for (auto c : pattern) { if (p2i.count(c) == 0) { i++; p2i[c] = i; } pat += to_string(p2i[c]); } unordered_map<string, int> str2i; i = 0; string pat1 = ""; for (auto c : words) { if (str2i.count(c) == 0) { i++; str2i[c] = i; } pat1 += to_string(str2i[c]); } return pat1 == pat; } }; main(){ Solution ob; cout << (ob.wordPattern("cbbc", "word pattern pattern word")); }
Input
"cbbc", "word pattern pattern word"
Output
1
- Related Articles
- Word Pattern II in C++
- How to match a particular word in a string using Pattern class in Java?
- Pattern pattern() method in Java with examples
- ORDERBY word in MySQL?
- Tribonacci Word in C++
- Word Ladder in C++
- Word Break in Python
- Word Search in Python
- Word Squares in C++
- Word Abbreviation in C++
- Answer in a word:
- Phyllotaxis pattern in Python?
- Adapter Pattern in C++?
- 132 Pattern in C++
- Number pattern in JavaScript
