第一题: 万万没想到之聪明的编辑
解题思路
1. 本题采用Java字符串的replaceAll()方法 及 正则表达式的使用
2. 关于正则表达式
(.)\\1+ 括号中的点表示任意字符,后面的\\1表示取第一个括号匹配的内容,
后面的加号表示匹配1次或1次以上
二者加在一起就是某个字符重复两次或两次以上
$1 取出匹配的第一个字符 $1$1 取出两次
(.)\\1(.)\\2 同理
package 字节跳动.R_2019春招_;
import java.util.Scanner;
public class R01_万万没想到之聪明的编辑 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
while (k-- > 0) {
String str = in.next();
System.out.println(str.replaceAll("(.){3,}","$1$1")
.replaceAll("(.)\\1(.)\\2","$1$1$2")
);
}
}
}
第二题:万万没想到之抓捕孔连顺
解题思路
1、 滑动窗口解题,因为数组有序 在左边左边确定的情况下 找到>d的第一个索引j
即除了i外 供选择的位置有 p=j-1-i个, p个位置选出两个 有 p*(p-1)/2 中方案
2. 再找出下一个窗口的方案数 相加即可
/**
* @author Ren
*/
import java.util.*;
public class R02_万万没想到之抓捕孔连顺 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = in.nextInt();
}
long count = 0;
for (int i = 0,j=i+2; i < n-2; i++) {
long p;
while (j < n && arr[j] - arr[i] <= d) {
j++;
} //j++后判断是否符合条件 故p要-1
p = j - i - 1;
// 确定了i的位置 之后的两个位置在范围内进行任意组合 p*(p-1)/2
count += (p*(p-1)/2);
}
System.out.println(count % 99997867);
}
}