终于做出来了
想了好几个方法发现还是有split方法最简单
下面是代码
package T1;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k=0;
k = sc.nextInt();//最长距离
//吃掉换行符
sc.nextLine();
String str = sc.nextLine();
String name1 ="Alice";
String name2 ="Bob";
String []words = str.split("\\s|\\.");
//以空格和.分割
int []wordslength = new int[words.length];
for (int i = 0; i < words.length; i++) {
wordslength[i] = words[i].length();
}
//分割后的长度
int count=0;
for (int i = 0; i < words.length; i++) {
int sum=1;
for (int j = i+1; j < words.length; j++) {
if(j==i+1) {
sum=1;
}
else {//1+上一个的长度+1
sum += words[j-1].length()+1;
}
if(words[i].equals(name1)) {
if(words[j].equals(name2)) {
if(sum<=k) {
count++;
}
}
}
if(words[i].equals(name2)) {
if(words[j].equals(name1)) {
if(sum<=k) {
count++;
}
}
}
}
}
System.out.println(count);
}
}
|