用C++ STL对长度为二的连续子字符串计数

给定一个字符串,任务是打印给定字符串中长度为2的所有不同子字符串。所有子字符串都应按字典顺序打印。 例如:

null
Input: str = "abcab"Output: ab-2        bc-1        ca-1Input: str = "xyz"Output: xy-1        yz-1

本文的目的是展示 地图 一对 在C++ STL中。 我们声明一个映射d_对,它使用一个字符对键和count作为值。我们迭代起始索引中的给定字符串,以存储尚未出现的每个连续对,并在映射中增加其计数。循环完成后,我们在映射容器中获得所有不同的连续对及其相应的出现计数。 请注意,使用map是因为我们需要按顺序输出。我们需要一个 无序地图 如果不需要按排序的顺序输出。欠序_map()操作的时间复杂度为O(1),而map的时间复杂度为O(logn)

CPP

// C++ STL based program to print all distinct
// substrings of size 2 and their counts.
#include<bits/stdc++.h>
using namespace std;
void printDistinctSubStrs(string str)
{
// Create a map to store unique substrings of
// size 2
map<pair< char , char >, int > dPairs;
// Count occurrences of all pairs
for ( int i=0; i<str.size()-1; i++)
dPairs[make_pair(str[i], str[i+1])]++;
// Traverse map to print sub-strings and their
// counts.
cout << "Distinct sub-strings with counts:" ;
for ( auto it=dPairs.begin(); it!=dPairs.end(); it++)
cout << it->first.first << it->first.second
<< "-" << it->second << " " ;
}
// Driver code
int main()
{
string str = "abcacdcacabacaassddssklac" ;
printDistinctSubStrs(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 

本文由 希曼苏·古普塔(巴格里) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享