เราได้รับกับสองสตริงเช่น 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
-
สำหรับการคำนวณจำนวนคู่ให้ใช้ฟังก์ชัน min() สำหรับ f1 และ f2
-
แสดงผล
ตัวอย่าง
#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