String repeated characters count

Problem

Write a C++ function to check string for repeated characters.

Count Repeated Characters in String

Algorithm

Using brute force we can start with the first character then compare it to the rest of the characters. If we can find a match then the string does have repeated characters otherwise we move to the next character and so on. If we finish all characters without finding a match then the string does not have repeated characters.

Code

Here is the brute force code

Solution

Another solution is to sort the string then loop through the string character by character and check for duplicates. We can borrow the merge sort code to sort the string (nlogn). Once the string is sorted we can check for duplicates in linear time.

Code

Here is the code to do that

Solution

Another solution is to calculate character counts. If there is a character with a count greater than one then the string contains repeated characters. An efficient way to calculate character counts is achieved by using hash tables. You can refer to the following post for more details.

Thanks for visiting. Please use the comments section below for feedback.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *