wu :: forums
« wu :: forums - first non repeated character in a string »

Welcome, Guest. Please Login or Register.
May 15th, 2024, 2:32pm

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: SMQ, towr, ThudnBlunder, Icarus, Grimbal, Eigenray, william wu)
   first non repeated character in a string
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: first non repeated character in a string  (Read 1948 times)
sat90
Newbie
*





   


Posts: 7
first non repeated character in a string  
« on: Aug 9th, 2011, 12:50am »
Quote Quote Modify Modify

find first non repeated character in a string in o(n) time and 0(1) space...
IP Logged
srikanth
Newbie
*





   


Posts: 1
Re: first non repeated character in a string  
« Reply #1 on: Aug 9th, 2011, 7:56am »
Quote Quote Modify Modify

Code:

char FindFirstNonDuplicate(char *s, int n)
{
char hash[256] = { 0 };
for(int i=0;i<n;i++) hash[s[i]]++;
for(int i=0;i<n;i++) if(hash[s[i]] ==  1) return s[i];
return -1    
}

 
I am not sure if it is O(1) space complicity because of hash.
IP Logged
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: first non repeated character in a string  
« Reply #2 on: Aug 9th, 2011, 8:58am »
Quote Quote Modify Modify

Yes, that qualifies as constant space, since it's a fixed size.
It wouldn't work for UTF-8 characters though, since those may consist of multiple bytes and then a 256 long hashtable is too small.
IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
sat90
Newbie
*





   


Posts: 7
Re: first non repeated character in a string  
« Reply #3 on: Aug 11th, 2011, 6:42am »
Quote Quote Modify Modify

@srikanth:
 
the above code finds sol for non repeated character in alphabetical order
 
test case: b a  
your output: a
 
expected output:b
IP Logged
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: first non repeated character in a string  
« Reply #4 on: Aug 11th, 2011, 10:12am »
Quote Quote Modify Modify

I think you're misreading his algorithm, it would return b as expected. He runs through the string twice, the second time returning the first character whose count in the hash is 1.
IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
sat90
Newbie
*





   


Posts: 7
Re: first non repeated character in a string  
« Reply #5 on: Aug 12th, 2011, 10:27am »
Quote Quote Modify Modify

sorry.........got it
IP Logged
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board