题解 | #记票统计#
记票统计
https://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int[][] arr1, arr2;
int[] cnt;
String a, b;
StringBuffer bu = new StringBuffer();
int n = 0, m = 0, i = 0;
try {
a = in.readLine();
n = parse1(a);
arr1 = new
int[n][2];// 人的名字数组,第一列是初始索引,第二列是名字长度
cnt = new int[n + 1];// 还包括无效票的票数
a = in.readLine();
parse2(a, arr1);
b = in.readLine();
m = parse1(b);
arr2 = new
int[m][2];// 票数组,第一列是初始索引,第二列是投票名字长度
b = in.readLine();
parse2(b, arr2);
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
getCnt(a, b, arr1, arr2, cnt, n, m);
while (i < n + 1) {
if (i < n)
bu.append(a.substring(arr1[i][0], arr1[i][0] + arr1[i][1]))
.append(" : ").append(cnt[i]).append("\n");
else
bu.append("Invalid : ").append(cnt[i]);
i++;
}
System.out.print(bu);
}
/**
* 计算单个数大小,无空格
* @param a
* @return
*/
public static int parse1(String a) {
int i = 0, l = a.length(), n = 0;
char[] charAy = new char[l];
a.getChars(0, l, charAy, 0);
while (i < l) {
n *= 10;
n += charAy[i] - '0';
i++;
}
return n;
}
/**
* 计算每个名字的初始索引和长度
* @param a
* @param arr1
*/
public static void parse2(String a, int[][] arr1) {
int i = 0, j = 0, l = a.length(), row = 0;
char[] charAy = new char[l + 1];
charAy[l] = ' ';
a.getChars(0, l, charAy, 0);
while (i < l + 1) {
if (charAy[i] == ' ') {
arr1[row][0] = i - j;
arr1[row++][1] = j;
j = 0;
} else
j++;
i++;
}
}
/**
*
* @param a 所有人的名字
* @param b 所有票的名字
* @param arr1
* @param arr2
* @param cnt
* @param n
* @param m
*/
public static void getCnt(String a, String b, int[][] arr1, int[][] arr2,
int[] cnt, int n, int m) {
int i = 0, j, k, index = 0, length = 0, index1 = 0, length1 = 0;
boolean f;
while (i < m) {//遍历所有投票的名字
index = arr2[i][0];
length = arr2[i][1];
j = 0;
f = false;
while (j < n) {//遍历所有的人的名字
index1 = arr1[j][0];
length1 = arr1[j][1];
if (length == length1) {
k = 0;
while (k < length) {
if (a.charAt(index1 + k) != b.charAt(index + k))
break;//有不等,跳出循环
k++;
}
if (k == length)//有相等,说明票投的是该人
f = true;
}
if (f) {//将j下标的人的票数+1
++cnt[j];
break;
}
j++;
}
if (!f)//遍历完所有的人,都没有名字相同的,就是无效票,cnt最后一个元素+1
++cnt[n];
i++;
}
}
}