用 C++ 列印兩個字串的公共字元(按字母順序)


在這個程式設計問題中,我們得到了兩個字串。我們需要找到這兩個字串中共同出現的字元,並**按字母順序列印這些公共字元**。如果找不到公共字元,則列印“未找到公共字元”。給定字串不包含所有小寫字母。

讓我們舉個例子:

Input : string1 : adsfhslf
   string2 : fsrakf
Output : affs

**說明**:這兩個字串之間有 a、f、s。因此,字典序輸出為“afs”。

Input : string1 : abcde
   string2 : glhyte
Output : No common characters

**說明**:沒有共同的字元。

為了解決這個問題,我們需要找到字串中的公共字元。輸出將是這些字串的字典序。

演算法

解決此問題的演算法如下:

Step 1 : Create two arrays a1[] and a2[] of size 26 each for counting the number of alphabets in the strings string1 and string2.
Step 2 : traverse a1[] and a2[]. and in sequence print all those numbers that have values in the array.

示例

讓我們根據此演算法建立一個程式來演示其工作原理:

 即時演示

#include<bits/stdc++.h>
using namespace std;
int main(){
   string string1 = "adjfrdggs";
   string string2 = "gktressd";
   cout<<"The strings are "<<string1<<" and "<<string2;
   cout<<"\nThe common characters are : ";
   int a1[26] = {0};
   int a2[26] = {0};
   int i , j;
   char ch;
   char ch1 = 'a';
   int k = (int)ch1, m;
   for(i = 0 ; i < string1.length() ; i++){
      a1[(int)string1[i] - k]++;
   }
   for(i = 0 ; i < string2.length() ; i++){
      a2[(int)string2[i] - k]++;
   }
   for(i = 0 ; i < 26 ; i++){
      if (a1[i] != 0 and a2[i] != 0){
         for(j = 0 ; j < min(a1[i] , a2[i]) ; j++){
            m = k + i;
            ch = (char)(k + i);
            cout << ch;
         }
      }
   }
   return 0;
}

輸出

The strings are adjfrdggs and gktressd
The common characters are : dgrs

更新於: 2020年1月3日

648 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告