蓝桥杯—人物相关性分析—简单粗暴

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);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@小红花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值