HackerRank in a String! Solution
We say that a string contains the word hackerrank if a subsequence of its characters spell the word hackerrank. For example, if string it does contain hackerrank, but does not. In the second case, the second r is missing. If we reorder the first string as , it no longer contains the subsequence due to ordering.
More formally, let be the respective indices of h, a, c, k, e, r, r, a, n, k in string . If is true, then contains hackerrank.
For each query, print YES on a new line if the string contains hackerrank, otherwise, print NO.
Function Description
Complete the hackerrankInString function in the editor below. It must return YES or NO.
hackerrankInString has the following parameter(s):
- s: a string
Input Format
The first line contains an integer , the number of queries.
Each of the next lines contains a single query string .
Constraints
Output Format
For each query, print YES on a new line if contains hackerrank, otherwise, print NO.
Sample Input 0
2
hereiamstackerrank
hackerworldSample Output 0
YES
NOExplanation 0
We perform the following queries:
The characters ofhackerrankare bolded in the string above. Because the string contains all the characters inhackerrankin the same exact order as they appear inhackerrank, we printYESon a new line.- does not contain the last three characters of
hackerrank, so we printNOon a new line.
Sample Input 1
hhaacckkekraraannk
rhbaasdndfsdskgbfefdbrsdfhuyatrjtcrtyytktjjtSample Output 1
YES
NO
Solution in Python
import re
def hackerrankInString(s):
return "YES" if re.search(".*".join(list("hackerrank")), s) else "NO"
for _ in range(int(input())):
print(hackerrankInString(input()))
Answer explanation
The code
".*".join(list("hackerrank"))
Creates the following regex pattern
'h.*a.*c.*k.*e.*r.*r.*a.*n.*k'
.* just means "0 or more of any character"
It's broken down into two parts:
. - a "dot" indicates any character
* - means "0 or more instances of the preceding regex token"
So it matches any word that has hackerrank in it such as
s ="h--ac++ke---zzz---r--ra??nk"
Without using regex
def hackerrankInString(s):
a = 0
for i in s:
if a<10 and i == "hackerrank"[a]:
a+=1
return "YES" if a==10 else "NO"
for _ in range(int(input())):
print(hackerrankInString(input()))
Answer Explanation
Assume our string is
"papahopackerank"
So we will be looping the above string
for i in "papahopackerank"
Initially a = 0 means "hackerrank"[0] = "h"
In our for loop once we find a "h" we will increase a. "papa" is completely ignored
After finding "h" it will increase a and now "hackerrank"[1] = "a" which means it will start searching "a" in rest of the string then "c" then "k" up to the end.
if a becomes 9 we can just break the loop and print "YES". Since a = 9 means we have found all letters of hackerrank.
In our example string, a will become 5 since it will match only up to "hacker". So our program will print "No"