You are given a matrix of characters. The matrix has N rows and M columns. Given a string s, you have to tell if it is possible to generate that string from a given matrix.
Rules for generating string from the matrix are:
- You have to pick the first character of the string from row 1, a second character from row 2, and so on. The the character of the string is to be picked from row 1, that is, you can traverse the rows in a cyclic manner (row 1 comes after row N).
- If an occurrence of a character is picked from a row, you cannot pick the same occurrence again from that row.
You have to print Yes if the given string can be generated from the matrix using the given rules, else print No.
Example:
Input: n = 3, m = 3, arr = {"aba", "xyz", "bdr"}, s = "axbaydb"
Output: Yes
Approach
C++
#include <bits/stdc++.h>using namespace std;void findTheString(int n, int m, vector<string> &arr, string s){int f[1005][26] = {0};for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){char c = arr[i][j];f[i][c - 'a']++;}}bool check = 1;for (int i = 0; i < s.size(); i++){int lev = i % n;if (f[lev][s[i] - 'a'])f[lev][s[i] - 'a']--;elsecheck = 0;}if (check){cout << "Yes\n";}else{cout << "No\n";}}int main(){int n = 3, m = 3;vector<string> arr = {"aba","xyz","bdr"};string s = "axbaydb";findTheString(n, m, arr, s);return 0;}
No comments:
Post a Comment