C++の辞書で特定のパターンに一致するすべての文字列を検索します
辞書と呼ばれる文字列のリストがあると考えてください。別のパターン文字列があります。私たちの仕事は、パターンに一致する文字列を見つけることです。辞書が[“ abb”、“ xyz”、“ aab”、“ kmm”]のようで、パターンが“ stt”であるとすると、結果は“ abb”、“ kmm”になります。パターンには最初に1つの文字があり、次に2つの同じ文字があるため、同じパターン文字列に従います。
この問題を解決するために、パターンに一致する辞書の単語がエンコード後のパターンと同じハッシュを持つように、パターンをエンコードします。辞書内のすべての単語を繰り返し処理し、ハッシュが同じ場所に表示します。
例
#include<iostream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
string stringEncode(string str) {
unordered_map<char, int> map;
string encoded_str = "";
int i = 0;
for (char ch : str) {
if (map.find(ch) == map.end())
map[ch] = i++;
encoded_str += to_string(map[ch]);
}
return encoded_str;
}
void matchedPattern(unordered_set<string> dict, string pattern) {
int patt_len = pattern.length();
string hash = stringEncode(pattern);
for (string word : dict) {
if (word.length() == patt_len && stringEncode(word) == hash)
cout << word << " ";
}
}
int main() {
unordered_set<string> dict = {"abb", "xyz", "aab", "kmm"};
string pattern = "stt";
matchedPattern(dict, pattern);
} 出力
kmm abb
-
C ++でa%b =kとなるような配列内のすべてのペア(a、b)を検索します
配列Aがあるとすると、その配列から、a%b =kとなるようにすべてのペア(a、b)を取得する必要があります。配列がA=[2、3、4、5、7]、k =3であるとすると、ペアは(7、4)、(3、4)、(3、5)、(3、7)になります。 これを解決するために、リストをトラバースして、指定された条件が満たされているかどうかを確認します。 例 #include <iostream> using namespace std; bool displayPairs(int arr[], int n, int k) { bool pairAvilable = true;
-
C++での文字列の配列
文字列の配列は、stringキーワードを使用してC++で作成できます。ここでは、このアプローチを使用したC++プログラムについて説明しています。 アルゴリズム Begin Initialize the elements of array by string keyword. And take string as input. Print the array. End. サンプルコード #include<iostream> #include<bits/stdc++.h> using namespace std; int main() { &nbs