题目:
这个题在蓝桥杯官网案例错误,所以没法判断代码得分。
思路:用两个list数组分别记录这两个字符串出现的位置,最后进行循环比较。要注意的是:判断字符出现是否是符号条件的位置(不能是一个单词的一部分)。
代码:
import java.util.ArrayList;
import java.util.Scanner;
public class H_人物相关性分析 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String str = sc.nextLine();
long res = 0;//结果
ArrayList<Integer> alice = po("Alice", str);//位置集
ArrayList<Integer> bob = po("Bob", str);//位置集
//System.out.println(alice);
//System.out.println(bob);
//判断alice字符的前面和后面位置
for (int i = 0; i < alice.size(); i++) {
for (int j = 0; j < bob.size(); j++) {
if (alice.get(i) - bob.get(j) <= n + 3 && alice.get(i) - bob.get(j) >= -n - 5) {
res++;
}
}
}
System.out.println(res);
}
//得到字符出现位置的集合
//s:目标字符串
//str:总字符串
public static ArrayList<Integer> po(String s, String str) {
ArrayList<Integer> list = new ArrayList<>();
int a = str.indexOf(s);//第一个出现位置
while (a != -1) {//当找不到目标字符串 indexof方法会返回-1
char z = str.charAt(a - 1);//前一个
char x = ' ';
if (a + s.length() < str.length()) {
x = str.charAt(a + s.length());//后一个
}
if (!xo(z) && !xo(x)) {
list.add(a);
}
a = str.indexOf(s, a + 1);
}
return list;
}
//判断一个字符是否是字母
public static boolean xo(char a) {
if (a >= 97 && a <= 122) {
return true;
}
if (a >= 65 && a <= 90) {
return true;
}
return false;
}
}