Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Word in string challenge

Sharing is caring!

Problem statement
We say that a string, s, contains the word hackerrank if a subsequence of the characters in s 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 p_0, p_1, \dots, p_9 be the respective indices of h, a, c, k, e, r, r, a, n, k in string s. If p_0 \textless p_1, \textless p_2 \dots \textless p_9 is true, then s contains hackerrank.

You must answer q queries, where each query i consists of a string, s_i. For each query, print YES on a new line if s_i contains hackerrank; otherwise, print NO instead.

Input Format
The first line contains an integer denoting q (the number of queries).
Each line i of the q subsequent lines contains a single string denoting s_i.

Output Format
For each query, print YES on a new line if s_i contains hackerrank; otherwise, print NO instead.

Sample Input 0

2
hereiamstackerrank
hackerworld

Sample Output 0

YES
NO

Solution

public class HackerrankInAString {
    public static void main(String[] args) throws FileNotFoundException {
        System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt"));
        Scanner in = new Scanner(System.in);

        int queries = in.nextInt();
        for (int q = 0; q < queries; q++) {
            char[] s = in.next().toCharArray();

            int cursor = 0;
            char[] hr = "hackerrank".toCharArray();
            for (int i = 0; i < s.length; i++) {
                if (s[i] == hr[cursor]) {
                    cursor++;
                }

                if (cursor == hr.length) {
                    System.out.println("YES");
                    break;
                }
            }

            if (cursor != hr.length) {
                System.out.println("NO");
            }
        }
    }
}