find repeated characters in a string
How would I go about finding the locations of the repeated character in a string(or array). say, if I have
HIMYDIFIWAI then, it will return 1,5,7,10 |
Well, one way I might do it is to make a dynamic array of structs. The struct would contain a counter and a character. Each time I find a new character I add it to the dynamic array of structs and set the counter for it's node to 1. Each time I have a repeat I would increment the counter for the character. Course, there is probably an easier way, I don't do well thinking about coding algorithms after 2 hours of tail gate partying:)
|
Since you never gave a language, here's one in perl
Code:
#!/usr/bin/perl |
The problem definition isn't very clear. No language specified, and is it always going to be just one character that's repeated in the string?
|
not one character. maybe more than one chars that are repeated.
language: java thx |
have the program loop through for each charector in the string checking if their are duplicates, skipping charAt(n) where n is the value of any char already defined as a duplicate of another.
|
A simpler way to do this would be to loop through the string once, keeping a mapping of the letters to their positions in the string. Then, once this is done, just check the mapping for letters with more than one position in the string. This is O(n) behavior.
|
I like Strikes idea, that was what I was trying to get at with my original post.
|
The python version (which is probably at least somewhat understandable to non-Pythoners who have some programming experience) would be:
Code:
s = "some string, of course" Code:
' ' -> [4, 12, 15] |
How about this, although admittedly only tested it on two different strings
Code:
import java.util.ArrayList; |
All times are GMT -5. The time now is 07:37 AM. |