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();
}
To check if two strings have the same characters:Use the sorted() function to sort the two strings. Use the equality operator to compare the results. If the comparison evaluates to True , the two strings have the same characters.
String Comparison using == in PythonThe == function compares the values of two strings and returns if they are equal or not. If the strings are equal, it returns True, otherwise it returns False.
3) By Using compareTo() method The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. Suppose s1 and s2 are two String objects. If: s1 == s2 : The method returns 0.
For an alternative solution, you can view the strings as enumerables and use Intersect()
like this:
public static string Common(string first, string second)
{
return new string((first.Intersect(second)).ToArray());
}
That's fine for a first approach, but you can make a few improvements, and there's a small error.
b
contains a character in a
that's already in c
, you'll repeat it.Set
to store the characters, since a Set
won't have repeats.+=
concatenation is usually inefficient; consider using a StringBuilder
or an analogous string-assembly class.a
or b
are 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With