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.
Input: str = "abcab" Output: ab-2 bc-1 ca-1 Input: str = "xyz" Output: xy-1 yz-1
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)
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
This article is contributed by Himanshu Gupta (Bagri). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print all distinct circular strings of length M in lexicographical order
- Substring in C++
- Count occurrences of a substring recursively
- Longest substring that starts with X and ends with Y
- Lexicographical Maximum substring of string
- Remove all consecutive duplicates from a string using STL in C++
- Sum of minimum difference between consecutive elements of an array
- Lexicographical smallest number after at most K consecutive swaps
- Find all distinct palindromic sub-strings of a given string
- Count of distinct remainders when N is divided by all the numbers from the range [1, N]
- Check if given string is a substring of string formed by repeated concatenation of z to a
- Print substring of a given string without using any string function and loop in C
- match_results length() in C++ STL
- Variable Length Argument in C
- Variable Length Arrays in C and C++
- The length of a string using pointers
- Variable length arguments for Macros
- 5 Different methods to find length of a string in C++
- C program to find the length of a string
- Find words which are greater than given length k using stringstream