- #1
SlurrerOfSpeech
- 141
- 11
I had a coding interview question that asked to write a function to determine whether one string is a substring of another. So I wrote
I realize that there's a potential performance bug with
because the entire substring on the right side is returned whereas string comparison only needs pointers/indices. What I'm saying is, if
then the substring doesn't need calculated because we already know there's a mismatch. My procedure has redundant operations.This is unless the compiler doesn't optimize in the way I know it could possibly do. I'm also not aware of anything in the C# standard library that would be the equivalent of
which is what I would need in this scenario.
Does what I'm asking make sense? What are your thoughts?
Code:
public bool IsSubtring ( String s1, String s2 )
{
// returns true or false depending on whether s1 is contained in s2
for ( m = s1.Length, int i = 0, j = (s2.Length - m + 1); i < j; ++i )
{
if ( s1 == s2.Substring(i,m) ) return true;
}
return false;
}
I realize that there's a potential performance bug with
Code:
s1 == s2.Substring(i,m)
because the entire substring on the right side is returned whereas string comparison only needs pointers/indices. What I'm saying is, if
Code:
s1[0] != s2[i]
then the substring doesn't need calculated because we already know there's a mismatch. My procedure has redundant operations.This is unless the compiler doesn't optimize in the way I know it could possibly do. I'm also not aware of anything in the C# standard library that would be the equivalent of
Code:
public bool strcmp ( string si, int ia, int ib, string sj, int ja, jb )
{
// checks whether the strings si and sj are equal in the range of
// indices [ia, ib) and [ja, jb) respectively
// ...
}
which is what I would need in this scenario.
Does what I'm asking make sense? What are your thoughts?