Saturday, 29 April 2017

Hacker Rank HackerRank in a String! Problem Solution.

Problem:
We say that a string, , contains the word hackerrank if a subsequence of the characters in  spell the word hackerrank. For example, haacckkerrannkk does contain hackerrank, but haacckkerannk does not (the characters all appear in the same order, but it's missing a second r).
More formally, let  be the respective indices of hackerrank in string . If  is true, then  contains hackerrank.
You must answer  queries, where each query  consists of a string, . For each query, print YES on a new line if  contains hackerrank; otherwise, print NO instead.
Input Format
The first line contains an integer denoting  (the number of queries). 
Each line  of the  subsequent lines contains a single string denoting .
Constraints
Output Format
For each query, print YES on a new line if  contains hackerrank; otherwise, print NO instead.
Sample Input 0
2
hereiamstackerrank
hackerworld
Sample Output 0
YES
NO
Explanation 0
We perform the following  queries:
  1.  
    The characters of hackerrank are bolded in the string above. Because the string contains all the characters in hackerrank in the same exact order as they appear in hackerrank, we print YES on a new line.
  2.  does not contain the last four characters of hackerrank, so we print NO on a new line.

Solution:

#include<bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    int n;
    string s,hacker = "hackerrank";
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> s;
        int res = 0;
        for(int j = 0; j < s.length(); j++){
            if(res < hacker.length() && j < s.length() && hacker[res] == s[j])res++;
        }

        if(res == hacker.length())cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

No comments:

Post a Comment