题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String a; try { a = r.readLine(); } catch (IOException e) { throw new RuntimeException(e); } char[] chs = a.toCharArray(); int i = 0, j = 0, n = 0, k = 0, in1 = 0, strl = 0, strIn, strCm, add, num = 0, t = 0, ans = 0; while (i < chs.length) { if (chs[i] == ' ') { i++; break; } n = n * 10; n += chs[i] - '0'; i++; } int[][] chIn = new int[n + 1][2]; while (i < chs.length) { if (k == 0) in1 = i;//长度为0,表示i为开始索引值 if (j == n + 1) break; if (chs[i] == ' ') { chIn[j][0] = in1;//存储开始索引 chIn[j][1] = k;//存储长度 i++; j++;//索引数组自增 k = 0;//长度重置为0 continue; } k++;//非空格字符串长度自增 i++; } while (i < chs.length) { k = k * 10; k += chs[i] - '0'; i++; } i = 0; int[] cnt = new int[128]; int[] bro = new int[n]; while (i < n) { strl = chIn[n][1];//被比较字符串长度 strIn = chIn[n][0];//被比较字符串开始索引 strCm = chIn[i][0];//比较字符串开始索引 if (strl == chIn[i][1] && noEql(chs, strCm, strIn, strl)) { j = 0; while (j < strl) {//兄弟单词,字母下标对消 ++cnt[chs[strIn + j]]; --cnt[chs[strCm + j]]; j++; } j = 0; add = 1; while (j < strl) { if (cnt[chs[strIn + j]] != 0 || cnt[chs[strCm + j]] != 0) {//有非0元素,表示不是兄弟单词 cnt[chs[strIn + j]] = 0;//重置为0 cnt[chs[strCm + j]] = 0;//重置为0 if (add == 1) add = 0; } j++; } if (add == 1) bro[num++] = chIn[i][0];//兄弟单词,兄弟单词个数num自增 } i++; } i = 0; while (i < num - 1) { j = 0; while (j < num - 1 - i) { if (comp(chs, bro[j], bro[j + 1], strl)) { t = bro[j]; bro[j] = bro[j + 1]; bro[j + 1] = t; } j++; } i++; } if (k <= num) { ans = bro[k - 1]; System.out.print(num + "\n" + a.substring(ans, ans + strl)); } else System.out.print(num); } //比较两字符串是否不相同 public static boolean noEql(char[] chs, int a, int b, int l) { int m = 0; boolean res = false; while (m < l) { if (chs[a + m] != chs[b + m]) { res = true; break; } m++; } return res; } //比较大小 public static boolean comp(char[] chs, int i1, int i2, int len) { int v = 0; boolean b = false; while (v < len) { if (chs[i1 + v] > chs[i2 + v]) { b = true; break; } else if (chs[i1 + v] == chs[i2 + v]) { v++; continue; } else break; } return b; } }