ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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
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.
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"
pos_map= {}
for pos, char in enumerate(s):
if char in pos_map:
pos_map[char].append(pos)
else:
pos_map[char] = [pos]
for char, pos_list in pos_map.items():
if len(pos_list) > 1:
print "%r -> %r" % (char, pos_list)
For that string ("some string, of course") above, this returns:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.