C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

与えられたシーケンスの最長プレフィックス一致を見つけるためのC++プログラム


ここでは、一連のシーケンス内のすべてのシーケンスに共通する最長のサブシーケンスを見つけるためのC++プログラムについて説明します。

アルゴリズム

Begin
Take the array of strings as input.
function matchedPrefixtill(): find the matched prefix between string s1 and s2 :
   n1 = store length of string s1.
   n2 = store length of string s2.
   for i = 0, j = 0 to i <= n1 – 1 && j <= n2 - 1
      if s1[i] != s2[j]
         break
      result.push_back(s1[i])
   return result
End
Begin
function matchedPrefix(): returns the longest matched prefix from the array of strings:
   for int i = 1 to n - 1
      pre = matchedPrefixtill(pre, a[i])
   return pre.
End

#include<bits/stdc++.h>
using namespace std;
string matchedPrefixtill(string s1, string s2) {
   string res;
   int n1 = s1.length(); //store length of string s1.
   int n2 = s2.length(); //store length of string s2.
   for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {    
      if (s1[i] != s2[j])
         break;
      res.push_back(s1[i]);
   }
   return (res);
}
string matchedPrefix (string a[], int n) {
   string pre = a[0];
   for (int i = 1; i <= n - 1; i++)
   pre = matchedPrefixtill(pre, a[i]);
   return (pre);
}
int main() {
   string a[] = {"Tutorialspoint", "Tutor", "Tutorials"}; //taking inputs
   int n = sizeof(a) / sizeof(a[0]);
   string res = matchedPrefix(a, n);
   if (res.length())
      cout<<"Longest common subsequence is matched - "<<res.c_str();
   else
      cout<<"No matched prefix";
   return (0);
}

出力

Longest common subsequence is matched - Tutor

  1. 文字列の長さを見つけるC++プログラム

    文字列は、ヌル文字で終了する1次元の文字配列です。文字列の長さは、ヌル文字の前の文字列の文字数です。 たとえば。 char str[] = “The sky is blue”; Number of characters in the above string = 15 文字列の長さを見つけるプログラムは次のとおりです。 例 #include<iostream> using namespace std; int main() {    char str[] = "Apple";    int co

  2. Pythonで指定された文字列シーケンスルールに従った後、n番目のシーケンスを見つけるプログラム

    2つの文字列s、tがあり、別の正の数nも与えられているとすると、シーケンスAのn番目の項を返す必要があります。ここで- A [0] =s A [1] =t A [n] =A [n-1] + A [n-2] nが偶数の場合、それ以外の場合はA [n] =A [n-2] +A[n-1]。 例として、s=aおよびt=bの場合、シーケンスAは-[a、 b、 ba( a + b)、 bba( b + ba)、 bbaba( bba + ba)] したがって、入力がs =pk、t =r、n =4の場合、出力は rrpkrpkになります。 これを解決するには、次の手順に従います-