Counts of distinct consecutive sub-string of length two using C++ STL - GeeksforGeeks
Given a string the task is to print all distinct sub-strings of length two in the given string. All substrings should be printed in lexicographical order.
Examples:
Input: str = "abcab" Output: ab-2 bc-1 ca-1 Input: str = "xyz" Output: xy-1 yz-1
We strongly recommend you to minimize your browser and try this yourself first.
The idea of this article is to demonstrate map and pair in C++ STL.
We declare a map d_pairs that uses a character pair key and count as value. We iterate over the given string from the starting index to store every consecutive pair if not present already and increment its count in the map. After completion of the loop, we get all distinct consecutive pairs and their corresponding occurrence count in the map container.
Please note that map is used as we need output in sorted order. We could use a unordered_map() if output was not needed in sorted order. Time complexity of underdered_map() operations is O(1) while that of map is O(Log n)
Read full article from Counts of distinct consecutive sub-string of length two using C++ STL - GeeksforGeeks
No comments:
Post a Comment