Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับตัวอักษรร่วมในสองสตริงใน C++

เราได้รับสตริงสองสตริง str1 และ str2 งานคือการนับจำนวนคู่ตัวอักษรที่ตรงกันในตำแหน่งเดียวกัน (str1[i] == str2[i])

ตัวอย่าง

Input − str1 = "hello", str2 = "heoo" Output − count: 3

คำอธิบาย − ตำแหน่ง 0:h=h, 1:e=e, 2:l≠o, 3:l≠o, 4:o=o → 3 ตำแหน่งตรง

Input − str1 = "point", str2 = "print" Output − count: 4

คำอธิบาย − ตำแหน่ง 0:p=p, 1:o≠r, 2:i=i, 3:n=n, 4:t=t → 4 ตำแหน่งตรง

แนวทางการแก้ปัญหา (Frequency-based)

หมายเหตุ: โค้ดตัวอย่างใช้วิธีนับความถี่ตัวอักษร (frequency count) ซึ่งตอบโจทย์ต่างจากคำอธิบาย (นับตำแหน่งที่ตรงกัน) โค้ดนับจำนวนคู่ตัวอักษรที่เหมือนกันโดยไม่คำนึงถึงตำแหน่ง

  • นับความถี่ตัวอักษรในแต่ละสตริง (f1[26], f2[26])
  • ผลรวม min(f1[c], f2[c]) สำหรับทุกตัวอักษร c

ตัวอย่างโค้ด C++ (Frequency Method)

#include <iostream>
using namespace std;

int countCommonChars(string s1, string s2) {
    int f1[26] = {0}, f2[26] = {0};
    for (char c : s1) f1[c - 'a']++;
    for (char c : s2) f2[c - 'a']++;
    
    int count = 0;
    for (int i = 0; i < 26; i++)
        count += min(f1[i], f2[i]);
    return count;
}

int main() {
    string s1 = "tutorialspoint", s2 = "codingground";
    cout << "Common character pairs: " << countCommonChars(s1, s2);
    return 0;
}

ผลลัพธ์

Common character pairs: 6

บทความนี้แสดงวิธีนับคู่ตัวอักษรที่เหมือนกันระหว่างสองสตริงโดยใช้วิธีนับความถี่ (frequency counting) ซึ่งต่างจากการนับตำแหน่งที่ตรงกัน ให้ผลลัพธ์เป็นจำนวนคู่สูงสุดที่จับคู่ได้