C++での2つの辞書単語の連結を使用した単語形成
この問題では、辞書と単語が与えられます。私たちの仕事は、与えられたワースが2つの辞書の単語の連結を使用して形成できるかどうかを確認することです。
与えられた単語を形成している間、単語の繰り返しは合法ではありません。
問題を理解するために例を見てみましょう
入力
dictionary = {“hello”, “tutorials”, “program” , “problem”, “coding”, “point”} word = “tutorialspoint” 出力
yes
説明
tutorialspoint is created using tutorials and point.
この問題を解決するために、辞書のすべての要素を、一般にトライと呼ばれるプレフィックスツリーに格納します。次に、トライ内の単語の接頭辞を検索します。見つかった場合は、2つに分割して、単語の他の部分を検索します。見つかった場合はtrueを返し、そうでない場合はfalseを返します。
ソリューションの実装を示すプログラム
例
#include<bits/stdc++.h>
using namespace std;
#define char_int(c) ((int)c - (int)'a')
#define SIZE (26)
struct TrieNode{
TrieNode *children[26];
bool isLeaf;
};
TrieNode *getNode(){
TrieNode * newNode = new TrieNode;
newNode->isLeaf = false;
for (int i =0 ; i< 26 ; i++)
newNode->children[i] = NULL;
return newNode;
}
void insert(TrieNode *root, string Key){
int n = Key.length();
TrieNode * pCrawl = root;
for (int i=0; i<n; i++){
int index = char_int(Key[i]);
if (pCrawl->children[index] == NULL)
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
pCrawl->isLeaf = true;
}
int prefixSearch(struct TrieNode *root, string key){
int pos = -1, level;
struct TrieNode *pCrawl = root;
for (level = 0; level < key.length(); level++){
int index = char_int(key[level]);
if (pCrawl->isLeaf == true)
pos = level;
if (!pCrawl->children[index])
return pos;
pCrawl = pCrawl->children[index];
}
if (pCrawl != NULL && pCrawl->isLeaf)
return level;
}
bool isWordCreated(struct TrieNode* root, string word){
int len = prefixSearch(root, word);
if (len == -1)
return false;
string split_word(word, len, word.length()-(len));
int split_len = prefixSearch(root, split_word);
return (len + split_len == word.length());
}
int main() {
vector<string> dictionary = {"tutorials", "program", "solving", "point"};
string word = "tutorialspoint";
TrieNode *root = getNode();
for (int i=0; i<dictionary.size(); i++)
insert(root, dictionary[i]);
cout<<"Word formation using dictionary is ";
isWordCreated(root, word)?cout<<"possible" : cout<<"not possible";
return 0;
} 出力
Word formation using dictionary is possible
-
C ++を使用して、N階乗の合計の最後の2桁を検索します。
ここでは、最後の2桁を取得する方法を説明します。 N階乗の合計の単位桁と10桁。したがって、N =4の場合、1になります。 + 2! + 3! + 4! =33.したがって、単位の場所は3で、10の場所は3です。結果は33になります。 10の後、10の場所は0のままになります。N=10以上の場合、00になります。階乗数のN=1から10のグラフを作成できます。 これらの手順を使用してこの問題を解決できます- nの値が10未満の場合、(1!+ 2!+…+ n!)mod 10 それ以外の場合、nの値が10以上の場合、(1!+ 2!+…+ 10!)mod 10 =13 例 #inc
-
C++のリンクリストを使用して2つの多項式を追加します。
この概念をよりよく理解するために、最初に必要なすべての基本的な内容をブラッシュアップしましょう。 リンクリスト リストのノードにオブジェクトとして各要素を格納するデータ構造です。すべてのメモには、2つの部分のデータハンと次のノードへのリンクが含まれています。 多項式 は変数と係数で構成される数式です。たとえば、x ^ 2-4x + 7 多項式リンクリスト 、多項式の係数と指数は、リストのデータノードとして定義されます。 リンクリストとして保存されている2つの多項式を追加します。同じ累乗の変数の係数を追加する必要があります。リンクリストノードには3つのメンバーが含まれ、係数値は次のノー