美团笔试0911 第一题。
题目
给一个字符串,其中有一些子串代表的数字为22的倍数,求这样的子串的个数。
解法
原理
把整个字符串从右往左遍历,记录从最右边开始的一位数、两位数、三位数...的余数。余数的值重复的次数就是满足题目条件的子串数。
例如
对字符串‘12221’,满足题目条件的子串个数为2。
从最右边开始,也就是从个位数开始:
1%22=1,
21%22=21,
221%22=1,
2221%22=21,
12221%22=11.
在遍历过程中,余数的值重复了两次,与子串个数相同。
实现
public static int solve2(int p, String s) {
int n = s.length();
int ans = 0;
// 开辟一个大小为p的数组,用于存储遍历字符串每一位的余数
int[] count = new int[p];
// 如果该子串的余数为0,则不需要等待与其重复的,它直接就可以满足条件了
count[0] = 1;
int tempRemain = 0;
for (int i = n-1; i >= 0; i--) {
String t = s.substring(i);
int val = Integer.valueOf(t);
tempRemain = val%p;
ans += count[tempRemain];
count[tempRemain]++;
}
System.out.println(ans);
return ans;
}