【問題描述】
小明正在分析
一
本小說中的人物相關性。他想知道在小說中 Alice 和 Bob
有多少次同時出現。
更准確的說,小明定義 Alice 和 Bob
“
同時出現
”
的意思是:在小說文本
中 Alice 和 Bob 之間不超過 K 個字符。
例如以下文本:
This is a story about Alice and Bob. Alice wants to send a private message to Bob.
假設 K
=
20,則 Alice 和 Bob 同時出現了 2 次,分別是
”
Alice and Bob
”
和
”
Bob. Alice
”
。前者 Alice 和 Bob 之間有 5 個字符,后者有 2 個字符。
注意:
1. Alice 和 Bob 是大小寫敏感的,alice 或 bob 等並不計算在內。
2. Alice 和 Bob 應為單獨的單詞,前后可以有標點符號和空格,但是不能
有字母。例如 Bobbi 並不算出現了 Bob。
【輸入格式】
第
一
行包含
一
個整數 K。
第二行包含
一
行字符串,只包含大小寫字母、標點符號和空格。長度不超
過 1000000。
【輸出格式】
輸出
一
個整數,表示 Alice 和 Bob 同時出現的次數。
【樣例輸入】
20
This is a story about Alice and Bob. Alice wants to send a private message to Bob.
試題H: 人物相關性分析 12第十屆藍橋杯大賽軟件類省賽 Java 大學 B 組
【樣例輸出】
2
【評測用例規模與約定】
對於所有評測用例,1 ≤ K ≤ 1000000。
import java.util.List; import java.util.ArrayList; import java.util.Scanner; import javax.swing.text.DefaultEditorKit.InsertBreakAction; public class Main { static List<String> list = new ArrayList();//用來保存分割后的字符串 static List<Integer> art = new ArrayList<>();//記錄.出現的位置 static int number = 0; public static void print() { for(String b:list) { System.out.println(b); } } public static void fun(String string) { int count = 0; char crt[] = string.toCharArray();//將字符串轉為字符數組 for(char b:crt) { if(b == ' ') count++; else if(b == '.') { art.add(count); count++; } } } public static void insert()//將'.'插入到list中。 { int sum = 0; for(int i:art) { sum++; list.add(i+sum,".");//將指定的元素添加到指定的位置 } } public static void lon(List<String> list2,int k)//判斷兩個之間長度是否小於k { int lonK = 0; for(String str1:list2) { lonK += str1.length(); } if(lonK<=k) { number++; } } public static void ifmanzu(int k)//判斷是否滿組條件的個數 { //list.sublList(0,3) //將字符串的0到3,取出來 int begin = 0; List<String> list1 = list.subList(begin, list.size()); while(true) { //System.out.println(list1); int a1 = list1.indexOf("Alice");//找出列表中Allice 第一次出現的位置 int b1 = list1.indexOf("Bob");//找到列表中Bob第一次出現的位置 if(a1==-1||b1==-1)//沒有同時出現的了 { break; } if(a1<b1)//表示a1在前面 { lon(list1.subList(a1+1, b1), k); list1.remove(a1);//移除 } else { lon(list1.subList(b1+1, a1), k); list1.remove(b1); } } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); int k = scanner.nextInt(); Scanner scanner1 = new Scanner(System.in); String string = scanner1.nextLine(); fun(string); //String [] a = string.split("\\s+");//按空格截取 String [] a = string.split("[ \\.]"); for(String b:a) { list.add(b); } insert();//將'.'插入到list中 ifmanzu(k); System.out.println(number); //System.out.println(art); } }