Thursday, February 18, 2021

HackerRank - Two Strings

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
world

Result YES

And one more for good measure:

hi
world

Result 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

3 comments:

  1. Fun88 Casino Review and Bonuses
    Check out our 퍼스트 카지노 fun88 Casino review for the complete info fun88 soikeotot and bonuses. Read how to claim the welcome bonus ラッキーニッキー and find out more! Play now! Rating: 4.9 · ‎Review by Vienne Garcia

    ReplyDelete
  2. A live supplier on-line casino 파라오카지노 도메인 may have a time restrict to keep the sport shifting at a good pace. Most live supplier casinos have a time restrict of around 30 seconds. The wagering requirement for the casino bonus is a 25x rollover, which is lower wagering necessities than similar bonuses from different on-line casinos. Researching on-line casinos within the USA may be an exhausting task.

    ReplyDelete
  3. Then we’ll see how US on-line roulette compares to roulette in physical casinos. And finally, we’ll present an intensive record of the US states where roulette is legal. The three variants are very comparable at 1xbet first glance, with solely slight variations in the betting options.

    ReplyDelete

HackerRank - SherlockAndAnagrams

Sherlock and Anagrams, oh what a title. Let’s see what HackerRank has in store for us next. This one is rated as medium and the blurb for it...