子词的定义如下:
给定由一个或多个由非单词字符分隔的单词组成的句子,处理查询,其中每个查询由单个字符串组成,。要处理每个查询,请计算所有句子中作为子词出现的次数,然后在新行上打印出现次数。
示例输入:
1
现有的悲观主义乐观主义者是这个
1
是
样品输出
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);
}
有人可以帮我弄清楚为什么上面的代码会给出错误的答案吗?
答案 0 :(得分:0)
这里有两件事要提到:
nextInt()
的调用不会消耗换行符,您必须显式调用nextLine()
或抓取整行并转换为 int (解释为{ {3}})is
中的两个isis
),您需要将\\w
替换为\\B
(非-word boundary)。查看here:
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
}