0

A Sub word is defined as follows:

  1. 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.
  2. It is preceded and succeeded by word characters only.

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

Sample input:
1
existing pessimist optimist this is
1
is
Sample output
3

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> s = new ArrayList();
for (int i = 0; i <= n; i++)
{
    String st = sc.nextLine();
    s.add(st);
}

int q = sc.nextInt();

for (int i = 0; i<q;i++)
{
    int count = 0;
    String st = sc.nextLine();
    String check = "\\w"+st+"\\w";
    Pattern p = Pattern.compile(check);
    for (int j = 0; j < n; j++)
    {
       Matcher m = p.matcher(s.get(j));
       while (m.find())
       {
           count += 1;
       }
   }

   System.out.println(count);
}

Can someone help me figure out why the above code gives wrong answer for the problem?

nbrooks
  • 17,489
  • 5
  • 46
  • 61
  • I think you need to do your own debugging. You understand what the different parts of your code were supposed to do, presumably. Either use an IDE debugger, or just print some stuff out, to see what statement might not be working the way you expect. If you find out where it's failing but don't understand why, then you can ask a better question. – ajb Aug 21 '17 at 02:06
  • Not to mention that your code apparently expects things to be on multiple lines, and the "sample input" you show us is all on one line. – ajb Aug 21 '17 at 02:07

1 Answers1

0

There are two things to mention here:

  • The call to nextInt() does not consume a line break, you must either explicitly call nextLine() or grab the whole line and convert to an int (it is explained here)
  • The regex won't match consecutive occurrences of the pattern (like two is in isis), you need to replace \\w with \\B (a non-word boundary).

See a fixed code snippet:

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // Force it to consume the line break
ArrayList<String> s = new ArrayList();
for (int i = 0; i < n; i++)
{
    String st = sc.nextLine();
    s.add(st);
}

int q = sc.nextInt();
sc.nextLine(); // Force it to consume the line break
for (int i = 0; i < q; i++)
{
    int count = 0;
    String st = sc.nextLine();
    String check = "\\B" + st + "\\B";
    Pattern p = Pattern.compile(check);
    for (int j = 0; j < n; j++)
    {
       Matcher m = p.matcher(s.get(j));
       while (m.find())
       {
           count += 1;
       }
   }
   System.out.println(count); // => 3
}
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397