题解 | #参数解析#
参数解析
https://www.nowcoder.com/practice/668603dc307e4ef4bb07bcd0615ea677
不知道用例里需要保证顺序.. 浪费了时间。
而且一开始没有想好具体的方案,还需要调试。
一共花费大概1小时40分钟。
时间用得比较久...
考虑过逐个字符来比较,遇到第一个引号和后一个匹配的引号取出值来,发现这样直接,没有办法判断第一个和后一个的位置;
考虑过用别的字符替换引号,测试过后发现这个想法还是不能解决全部的问题;
最后采用替换加取引号内内容的方法弄出来了。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
/**
* 参数解析
* xcopy~/s~"C:\\program~files"~"d:\"
* xcopy /s "C:\\program files" "d:\"
*/
public class ParamParse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String nextLine = scanner.nextLine();
List<String> result = new ArrayList<>();
LinkedList<Integer> locations = new LinkedList<>();
while (true) {
int indexOf = nextLine.indexOf("\"");
if (indexOf != -1) {
nextLine = nextLine.replaceFirst("\"", "!");
locations.add(indexOf);
} else {
break;
}
}
List<String> quetList = new ArrayList<>();
while (!locations.isEmpty()) {
Integer beforeIndex = locations.pop();
Integer afterIndex = locations.pop();
quetList.add(nextLine.substring(beforeIndex + 1, afterIndex));
}
nextLine = nextLine.replace(" ", "~");
String[] split = nextLine.split("!");
for (String str : split) {
if (!str.equals("~")) {
String replaceOtherStr = str.replace("~", " ");
if (quetList.contains(replaceOtherStr)) {
// 为保证顺序,包含就加入到result中
result.add(replaceOtherStr);
} else {
String[] splitOther = replaceOtherStr.split(" ");
for (String s : splitOther) {
if (s.equals(" ") || s.length() == 0) {
continue;
} else {
result.add(s);
}
}
}
}
}
System.out.println(result.size());
for (String str : result) {
System.out.println(str);
}
}
}
}

