1、问题描述
【问题描述】
小明正在分析一本小说中的人物相关性。他想知道在小说中 Alice 和 Bob
有多少次同时出现。
更准确的说,小明定义 Aice 和Bob“同时出现” 的意思是:在小说文本
中 Alice 和Bob之间不超过下个字符。
例如以下文本:
This is a story about Alice and Bob. Alice wants to send a private message to Bob.
假设飞=20,则Alice 和Bob 同时出现了2次,分别是”Alice and Bob”
和”Bob. Alice”。前者 Alice 和Bob 之间有5个字符,后者有2个字符。
注意:
1. Alice 和Bob 是大小写敏感的,alice 或bob 等并不计算在内。
2. Alice 和Bob 应为单独的单词,前后可以有标点符号和空格,但是不能
有字母。例如Bobbi 並不算出现了 Bob。
【输入格式】
第一行包含一个整数下。
第二行包含一行字符串,只包含大小写字母、标点符号和空格。长度不超
1000000
【样例输入】
20
This is a story about Alice and Bob. Alice wants to send a private message to Bob.
【样例输出】
2
2、代码实现
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int K = scanner.nextInt();
//读换行
scanner.nextLine();
//不能用 scanner.next(); 因为字符串里面有空格
String[] words = scanner.nextLine().split("\\s+|\\.");
long ans = 0;
for(int i = 0;i < words.length;i++) {
if("Alice".equals(words[i])) {
for(int j = i + 1;j < words.length;j++) {
if("Bob".equals(words[j])) {
//这个1表示Alice后面的空格或符号
int distance = 1;
for(int k = i + 1;k < j;k++) {
//每次的+1都是这个单词后面的空格或符号
distance += words[k].length() + 1;
}
if(distance <= K) {
ans++;
}
}
}
}
}
for(int i = 0;i < words.length;i++) {
if("Bob".equals(words[i])) {
for(int j = i + 1;j < words.length;j++) {
if("Alice".equals(words[j])) {
//这个1表示Bob后面的空格或符号
int distance = 1;
for(int k = i + 1;k < j;k++) {
//每次的+1都是这个单词后面的空格或符号
distance += words[k].length() + 1;
}
if(distance <= K) {
ans++;
}
}
}
}
}
System.out.println(ans);
}
}