C++ 中兩個字串的公共字元計數
假設我們有兩個字串,分別稱為 str1 和 str2,任務是找到這兩個字串中公共字元的數量,即如果 str1[i] = str[j],則它們將被視為一對,計數增加 1;如果 str1[i]!=str2[j],則它們不會被視為一對,計數不會增加 1。
例如
Input − str1 = “hello” str2 = “heoo” Output − count is: 3
解釋− str1[0] = str2[0] 即 h;str1[1] = str2[1] 即 e;str1[2]!=str2[2] 即 l 和 o;str1[3]=str2[3] 即 o。因此,具有相似字母的對有 3 對,1 對包含不同的字母。
Input − str1 = “point” str2 = “print” Output − count is: 4
解釋− str1[0] = str2[0] 即 p;str1[1] != str2[1] 即 o 和 r;str1[2] =str2[2] 即 i;str1[3]=str2[3] 即 n;str1[4]=str2[4] 即 t。因此,具有相似字母的對有 4 對,1 對包含不同的字母。
下面程式中使用的方案如下
輸入兩個字串 str1 和 str2
使用 length() 函式計算兩個字串的大小,該函式將根據字串中的字母數(包括空格)返回一個整數值。
最初,將兩個字串中字元的頻率初始化為 0。
現在,為了更新 str1 的頻率,應用“f1[str1[i] - 'a']++”,這將隨著每次迭代增加頻率,並對 str2 應用相同的過程
為了計算對的數量,對 f1 和 f2 應用 min() 函式。
顯示結果
示例
#include <iostream>
using namespace std;
// Function to count the valid indices pairs
int pairs(string str1, int size1, string str2, int size2){
// f1 and f2 for frequencies of characters
// of string str1 and str2
int f1[26] = { 0 };
int f2[26] = { 0 };
// 'c' To count the valid pairs
int i, c = 0;
//updating the frequencies of str1 and st2
for (i = 0; i < size1; i++){
f1[str1[i] - 'a']++;
}
for (i = 0; i < size2; i++){
f2[str2[i] - 'a']++;
}
// Find the count of valid pairs
for (i = 0; i < 26; i++){
c += (min(f1[i], f2[i]));
}
return c;
}
// main function
int main(){
string str1 = "tutorialspoint", str2 = "codingground";
int size1 = str1.length(), size2 = str2.length();
cout<<”Total pairs with str1[i]=str2[j] are: ”;
cout << pairs(str1, size1, str2, size2);
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Total pairs with str1[i]=str2[j] are − 6
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP