Our next challenge from HackerRank is to see if two strings contain a common substring, it goes on to say that substring could even just be one letter. Again, this one is rated as easy and I hope it lives up to that.
The initial boilerplate to plug things into:
static string twoStrings(string s1, string s2) {
}
And a test case:
hello
worldResult YES
And one more for good measure:
hi
worldResult NO
My first attempt at it involves breaking one of the strings into a char array so that I can use IndexOfAny
which only takes in a char array. Converting string to char array is very easy since there is a ToCharArray
method on string. Lets see how this looks and run it against their tests:
static string twoStrings(string s1, string s2)
{
var charsOfFirstWord = s1.ToCharArray();
var index = s2.IndexOfAny(charsOfFirstWord);
var success = index > -1;
return success ? "YES" : "NO";
}
Initial tests pass and then running it against the full suite, they also pass! Huzzah! This one really was easy. Whew, nice change from that last one.
We could tidy this up a bit more to reduce the number of lines. In fact we could one line this (though I question readability) into:
static string twoStrings(string s1, string s2)
{
return s2.IndexOfAny(s1.ToCharArray()) > -1 ? "YES" : "NO";
}
You can find this test at HackerRank - Two Strings
No comments:
Post a Comment