Problem
No. 13 - First Character Appearing Only OnceImplement a function to find the first character in a string which only appears once.
For example: It returns ‘b’ when the input is “abaccdeff”.
Solution Least Time
Character getFirstUnique(char[] w)
{
HashMap m = new LinkedHashMap();
for(int i=0; i< w.length; i++)
{
Integer cnt = m.get(w[i]);
if(cnt == null) m.put(w[i], 1);
else m.put(w[i], cnt+1);
}
for(int i=0; i< w.length; i++)
{
if(m.get(w[i]) == 1) return w[i];
}
return null;
}
Solution Least Space
public Character solnNoMem(char[] w)
{
for(int i=0; i< w.length; i++)
{
int cnt = 0;
for(int j=0; j< w.length; j++)
{
if(i!=j && w[i] == w[j]) {
cnt =1; break;
}
}
if(cnt==0) return w[i];
}
return null;
}
No comments:
Post a Comment