I got this homework. And have solved it in following way. I need your comments whether it is a good approach or I need to use any other data sturcture to solve it in better way.
public string ReturnCommon(string firstString, string scndString)
{
StringBuilder newStb = new StringBuilder();
if (firstString != null && scndString != null)
{
foreach (char ichar in firstString)
{
if (!newStb.ToString().Contains(ichar) && scndString.Contains(ichar))
newStb.Append(ichar);
}
}
return newStb.ToString();
}
That’s fine for a first approach, but you can make a few improvements, and there’s a small error.
bcontains a character inathat’s already inc, you’ll repeat it.Setto store the characters, since aSetwon’t have repeats.+=concatenation is usually inefficient; consider using aStringBuilderor an analogous string-assembly class.aorbare empty, you don’t have to do any work at all! Just return an empty string.You can think about some more sophisticated improvements, too, by imagining how your algorithm scales if you started to use huge strings. For example, one approach might be that if one string is much longer than the other, you can sort the longer one and remove duplicates. Then you can do a binary search on the characters of the shorter string very quickly.