java - Sub Word in a String -


a sub word defined follows:

  1. a sequence of word characters (i.e., english alphabetic letters, digits, and/or underscores) occur in same exact order (i.e., contiguous sequence) inside word.
  2. it preceded , succeeded word characters only.

given sentences consisting of 1 or more words separated non-word characters, process queries each query consists of single string, . process each query, count number of occurrences of sub-word in sentences, print number of occurrences on new line.

sample input:
1
existing pessimist optimist is
1
is
sample output
3

scanner sc = new scanner(system.in); int n = sc.nextint(); arraylist<string> s = new arraylist(); (int = 0; <= n; i++) {     string st = sc.nextline();     s.add(st); }  int q = sc.nextint();  (int = 0; i<q;i++) {     int count = 0;     string st = sc.nextline();     string check = "\\w"+st+"\\w";     pattern p = pattern.compile(check);     (int j = 0; j < n; j++)     {        matcher m = p.matcher(s.get(j));        while (m.find())        {            count += 1;        }    }     system.out.println(count); } 

can me figure out why above code gives wrong answer problem?

there 2 things mention here:

  • the call nextint() not consume line break, must either explicitly call nextline() or grab whole line , convert int (it explained here)
  • the regex won't match consecutive occurrences of pattern (like 2 is in isis), need replace \\w \\b (a non-word boundary).

see fixed code snippet:

scanner sc = new scanner(system.in); int n = sc.nextint(); sc.nextline(); // force consume line break arraylist<string> s = new arraylist(); (int = 0; < n; i++) {     string st = sc.nextline();     s.add(st); }  int q = sc.nextint(); sc.nextline(); // force consume line break (int = 0; < q; i++) {     int count = 0;     string st = sc.nextline();     string check = "\\b" + st + "\\b";     pattern p = pattern.compile(check);     (int j = 0; j < n; j++)     {        matcher m = p.matcher(s.get(j));        while (m.find())        {            count += 1;        }    }    system.out.println(count); // => 3 } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -