HackerRank Find a Sub Word Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Find a Sub Word Solution. This problem is a part of the Regex HackerRank Series.

Ezoicreport this adHackerRank Find a Sub Word Solution
HackerRank Find a Sub Word Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Find a Sub Word Solution

Problem

We define a word character to be any of the following:

  • An English alphabetic letter (i.e., a-z and A-Z).
  • A decimal digit (i.e.0-9).
  • An underscore (i.e., _, which corresponds to ASCII value 95).

We define a word to be a contiguous sequence of one or more word characters that is preceded and succeeded by one or more occurrences of non-word-characters or line terminators. For example, in the string I l0ve-cheese_?, the words are Il0ve, and cheese_.

We define a sub-word as follows:

  • A sequence of word characters (i.e., English alphabetic letters, digits, and/or underscores) that occur in the same exact order (i.e., as a contiguous sequence) inside another word.
  • It is preceded and succeeded by word characters only.

Given n sentences consisting of one or more words separated by non-word characters, process q queries where each query consists of a single string, s. To process each query, count the number of occurrences of s as a sub-word in all n sentences, then print the number of occurrences on a new line.

Input Format

The first line contains an integer, n, denoting the number of sentences.
Each of the n subsequent lines contains a sentence consisting of words separated by non-word characters.
The next line contains an integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains a string, si, to check.

Constraints

  • 1 <= n <= 100
  • 1 <= q <= 10

Output Format

For each query string, si, print the total number of times it occurs as a subword within all words in all n sentences.

Sample Input

1
existing pessimist optimist this is
1
is

Sample Output

3

Explanation

We must count the number of times s = is occurs as a sub-word in our n = 1 input sentence(s):

  • s occurs 1 time as a sub-word of existing.
  • s occurs 1 time as a subword of pessimist.
  • s occurs 1 time as a sub-word of optimist.
  • While s is a substring of the word this, it’s followed by a blank space; because a blank space is non-alphabetic, non-numeric, and not an underscore, we do not count it as a sub-word occurrence.
  • While s is a substring of the word is in the sentence, we do not count it as a match because it is preceded and succeeded by non-word characters (i.e., blank spaces) in the sentence. This means it doesn’t count as a sub-word occurrence.

Next, we sum the occurrences of s as a sub-word of all our words as 1 + 1 + 1 + 0 + 0 = 3. Thus, we print 3 on a new line.

Ezoicreport this adHackerRank Find a Sub Word Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
using namespace std;

bool chK(char ch)
{
    if(ch>='a' && ch<='z' )
        return true;
    if(ch>='A' && ch<='Z')
        return true;
    if(ch>='0' && ch<='9')
        return true;
    if(ch=='_')
        return true;
   return false;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int i,j,num,test;
    string str,in;
    vector<string> list;
    
    cin>>num;
    getchar();
    
    while(num--)
    {
        getline(cin,in);
        
        //making the list of all the word given
        list.push_back(in);
    }
    
    cin>>test;
    
    for(int t=1;t<=test;t++)
    {
        cin>>str;
        int cnt=0;
        for(i=0;i<list.size();i++)
        {
            int p=0;
            bool prec=false;
            char ch;
            for(j=0;j<list[i].size();j++)
            {
                if(p==str.size())
                {
                    if(chK(list[i].at(j)) && prec==true)
                    {
                        cnt++;
                        //cout<<ch<<str<<list[i].at(j)<<endl;
                    }
                    p=0;
                    prec=false;
                }
                
                if(list[i].at(j)==str.at(p))
                {
                    if(p==0 && j>=1 && chK(list[i].at(j-1)))
                    {
                        prec=true;
                        ch=list[i].at(j-1);
                    }
                    if(prec==true)
                        p++;
                    else
                        p=0;
                }
                else
                {
                    if(p>=1)
                        j--;
                    p=0;
                    prec=false;
                    
                }
            }
        }
        
        cout<<cnt<<endl;
    }
    
    return 0;
}

HackerRank Find a Sub Word Solution in Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(br.readLine());
		String inputs[] = new String[n];
		for (int i = 0; i < inputs.length; i++) {
			inputs[i] = br.readLine();
		}

		int testWords = Integer.parseInt(br.readLine());
		String regex_right="\\w.*";
		String regex_left=".*\\w";
		while (testWords > 0) {
			int count = 0;
			String word=br.readLine();
			for (int i = 0; i < inputs.length; i++) {
				String arr[] = inputs[i].split(" ");
				for (int j = 0; j < arr.length; j++) {
					//System.out.println(arr[j]+" is "+arr[j].matches(regex_left+"is"+regex_right));
					if (arr[j].matches(regex_left+word+regex_right)) {
						count++;
					}
				}
			}
			System.out.println(count);
			testWords--;
		}

	}
}

HackerRank Find a Sub Word Solution in Python

import re
n = int(raw_input())
words = []
for i in range(0, n):
    words += re.split("[^a-zA-Z0-9_]+", raw_input())
t = int(raw_input())
for i in range(0, t):
    s = raw_input()
    count = 0
    for w in words:
        if (re.match("[a-zA-Z0-9_]+"+s+"[a-zA-Z0-9_]+", w)): count += 1
    print count
Ezoicreport this ad

HackerRank Find a Sub Word Solutions in JavaScript

process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) {
	input = input.split('\n');
	var n = parseInt(input[0]),
		t = parseInt(input[n+1]),
		ts = n+2,
		strs = input.slice(1,n+1).join(' ').split(' '),
		tc = input.slice(ts,ts+t),
		tcc = new Array(),
		c = 0, r, m = false;
	for (i=0, j=tc.length; i<j; i+=1) {
		c = 0;
		r = new RegExp('(?:\\w+'+tc[i]+'\\w+)','ig');
			for (ii=0, jj=strs.length; ii<jj; ii+=1) {
				m = strs[ii].match(r);
				if (m) {
					c += m.length;
				}
			}
		console.log(c);
	}
});

HackerRank Find a Sub Word Solutions in PHP

<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
fscanf($_fp, "%d", $m);
$lines = array();
for ($i = 0; $i < $m; $i++) {
    $lines[] = fgets($_fp);
}
$lines = preg_split('/[^0-9a-z_]+/', implode(' ', $lines));
$lines = implode(' ', $lines);
fscanf($_fp, "%d", $m);
$searches = array();
for ($i = 0; $i < $m; $i++) {
    $searches[] = trim(fgets($_fp));
}
foreach ($searches as $search) {
    $search = '/[0-9a-z_]' . $search . '[0-9a-z_]/';
    print preg_match_all($search, $lines, $matches) . PHP_EOL;
}

Disclaimer: This problem (Find a Sub Word) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Alien Username Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad