用 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP