题解 | #参数解析#
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; 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, l = chs.length, n1 = 0, n2 = 0, i1, i2 = -1, cnt = 0, inc = 1; int[] indx1 = new int[1000];//初始化空格所在下标的索引数组 int[] indx2 = new int[1000];//初始化引号所在下标的索引数组 while (i < l) { if (chs[i] == ' ') indx1[n1++] = i;//输入字符串中字符为空格,则将其索引放入数组,数组长度n1自增 if (chs[i] == '"') indx2[n2++] = i;//输入字符串中字符为空格,则将其索引放入数组,数组长度n2自增 i++; } indx1[n1++] = l;//空格索引数组中最后加入字符串长度为了截取最后一个字符串 i = 0; while (i < n2 - 1) {//遍历引号下标数组,引号成对出现,因此n2为偶数,成对遍历 j = 1; while (j < n1 - 1) {//遍历空格数组,如若空格的索引处于两引号索引之间,则无效,空格索引置为-1 if (indx1[j] > indx2[i] && indx1[j] < indx2[i + 1]) indx1[j] = -1; j++; } i += 2;//加2,循环一次跳过两个元素,因为引号成对,其索引也成对 } i = 0; a = "";//初始化字符串的引用 while (i < n1) { if (indx1[i] != -1) {//如果当前的空格索引不为-1,表示有效 cnt++;//数量+1 //i2初始为-1.第一个字符串的开始位置是虚设的,i2+inc(初始为1)表示从虚设的空格位置+1,刚好为字符串索引为0的起始位置 i1 = i2 + inc;//inc表示前面一对索引是否有引号,引号会导致字符串初始索引等于上个字符串结尾索引右移2位 i2 = indx1[i];//字符串结束索引为空格位置 inc = 1;//移位重置为1 } else {//为-1.无效空格,跳过循环 i++; continue; } j = 0; while (j < n2 - 1) {//遍历引号数组,当字符串的开始索引位置(空格位+inc)是引号开始时,且字符串结束位置(空格位)是引号后一位时,要将引号去掉 if (indx2[j] == i1 && indx2[j + 1] == i2 - 1) { i1++; i2--; inc = 2;//下个字符串的初始位置要+2,跳过引号和空格 } j += 2; } a = a + new String(chs, i1, i2 - i1) + "\n"; i++; } a = cnt + "\n" + a; System.out.print(a); } }