题解 | #参数解析#
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
// 注意 hasNext 和 hasNextLine 的区别
while ((str = br.readLine()) != null) { // 注意 while 处理多个 case
ArrayList<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '"') {
//匹配""里面的字符
for (++i; i < str.length(); i++) {
if (str.charAt(i) == '"') {
list.add(sb.toString());
sb.setLength(0);
sum++;
i++;
break;
}
sb.append(str.charAt(i));
}
//字符匹配结束标志:' '
} else if (str.charAt(i) == ' ' && sb.length() > 0) {
list.add(sb.toString());
sum++;
sb.setLength(0);
//字符到达末尾,匹配结束
} else if (i == str.length() - 1) {
sb.append(str.charAt(i));
list.add(sb.toString());
sum++;
//当用多个空格隔开字符时
} else if (str.charAt(i) == ' ' && sb.length() == 0) {
continue;
} else {
sb.append(str.charAt(i));
}
}
System.out.println(sum);
for (String s : list) {
System.out.println(s);
}
}
}
}
复杂度分析:
时间复杂度:O(n), 其中n为命令字符串的长度,需要遍历n个命令。
空间复杂度:O(1), 直接判断,无额外空间。