【问题标题】:Sub Word in a String字符串中的子词
【发布时间】:2017-08-21 01:45:29
【问题描述】:

子词定义如下:

  1. 在另一个单词中以相同的确切顺序(即连续序列)出现的单词字符序列(即英文字母、数字和/或下划线)。
  2. 它的前后只能是单词字符。

给定由一个或多个由非单词字符分隔的单词组成的句子,处理每个查询由单个字符串组成的查询,.要处理每个查询,请计算所有句子中作为子词的出现次数,然后在新行上打印出现次数。

样本输入:
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);
}

谁能帮我弄清楚为什么上面的代码给出了错误的答案?

【问题讨论】:

  • 我认为你需要自己调试。您大概了解代码的不同部分应该做什么。要么使用 IDE 调试器,要么只打印一些东西,看看哪个语句可能没有按您期望的方式工作。如果您发现它失败的地方但不明白为什么,那么您可以提出一个更好的问题。
  • 更不用说您的代码显然期望内容位于多行上,而您向我们展示的“示例输入”都在一行上。

标签: java regex


【解决方案1】:

这里有两点要提:

  • nextInt() 的调用不消耗换行符,您必须显式调用nextLine() 或获取整行并转换为int(解释为here
  • 正则表达式不会匹配连续出现的模式(例如isis 中的两个is),您需要将\\w 替换为\\B(非单词边界)。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2014-03-15
    • 2023-04-03
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2014-01-07
    • 2023-03-24
    相关资源
    最近更新 更多