Saturday, December 29, 2007

Google Interview Question - Part 7

Here is another question:

Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.

And here is the answer:

A:

private static String match(String a, String b)

{

String result = "";

Set lettersSet = new HashSet(26);

for (int i=0; i

lettersSet.add(new Character(b.charAt(i)));

}

for (int i=0; i

if (lettersSet.contains(new Character(a.charAt(i)))) {

result=result+a.charAt(i);

}

}

return result;

}

1 comment:

JP said...

Hi,

Thanks for sharing this question.

Please share more questions if you know.

Thanks
Prashant Jalasutram
http://prashantjalasutram.blogspot.com/

Links

 
RSS Feeds Submission Directory