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

นับซับสตริงติดกันที่แตกต่างกันความยาว 2 ด้วย C++ STL


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมนับซับสตริงติดกันที่แตกต่างกัน (distinct consecutive sub-string) ความยาว 2 โดยใช้ C++ STL

ให้สตริงหนึ่ง เราต้องนับและพิมพ์ซับสตริงที่ไม่ซ้ำกันทั้งหมดที่มีความยาว 2 จากสตริงที่ให้มา

ตัวอย่างโค้ด

#include <bits/stdc++.h> 
using namespace std; 

void calc_distinct(string str) {
    map<pair<char,char>, int> dPairs;
    for (int i = 0; i < str.size() - 1; i++) {
        dPairs[make_pair(str[i], str[i+1])]++;
    }
    cout << "Distinct sub-strings with counts:\n";
    for (auto it = dPairs.begin(); it != dPairs.end(); it++) {
        cout << it->first.first << it->first.second << "-" << it->second << " ";
    }
}

int main() {
    string str = "abcacdcacabacaassddssklac";
    calc_distinct(str);
    return 0;
}

เอาต์พุต

Distinct sub-strings with counts: aa-1 ab-2 ac-4 as-1 ba-1 bc-1 ca-4 cd-1 dc-1 dd-1 ds-1 kl-1 la-1 sd-1 sk-1 ss-2