欢迎访问我的CCF认证解题目录
题目描述
思路过程
总结一下题目信息
- 格式字符串:如果有参数,则后面带":"
- 命令行第一个为工具名,不用理
- 遇到不合法的参数或选项时,终止操作
- 如果出现多次,只输出最后一次
- 有参数的选项:-小写字母 参数(由小写字母,数字和减号组成的非空字符串)
- 无参数:-小写字母
我们可以用HashMap<String, Boolean>存储格式字符串的信息,当作字典使用,使用HashMap<String, String>存储结果集
对于每一个命令行,我们先用map判断选项是否在字典中,如果不存在,则说明选项不合法,结束该命令行
接着判断是否需要参数,如果需要参数且有给合法的参数,则填入结果集,否则结束
如果不需要参数,则直接填入
输出时,使用for循环从'a'到'z'进行遍历(保证按升序输出),如果存在于结果集中,则输出
代码
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<String, Boolean> map = new HashMap<String, Boolean>();//字典
HashMap<String, String> ans = new HashMap<String, String>();//结果
String temp = in.nextLine();
//输入字典
for ( int i = 0; i < temp.length(); i++ ) {
if ( i+1 < temp.length() && temp.charAt(i+1) == ':' ) {
map.put("-"+temp.charAt(i), true);
i++;
} else map.put("-"+temp.charAt(i), false);
}
int n = in.nextInt();
in.nextLine();
//开始判断
for ( int i = 0; i < n; i++ ) {
String[] arrs = in.nextLine().split(" ");
for ( int j = 1; j < arrs.length; j++ ) {
if ( map.containsKey(arrs[j]) ) {//合法选项
//有参数且参数合法
if ( map.get(arrs[j]) && j+1 < arrs.length && arrs[j+1].matches("[a-z0-9-]+")) {
ans.put(arrs[j], arrs[j+1]);
j++;
} else if ( !map.get(arrs[j]) ) ans.put(arrs[j], "");//不需要参数
else break;//需要参数,但没给参数,或参数不合法
} else break;
}
//输出
System.out.print("Case "+(i+1)+": ");
for ( char c = 'a'; c <= 'z'; c++ ) {//从小到大遍历
if ( ans.containsKey("-"+c) ) {
System.out.print("-"+c+" ");
//如果有参数
if ( !ans.get("-"+c).equals("") ) System.out.print(ans.get("-"+c)+" ");
}
}
System.out.println();
ans.clear();//情况结果集
}
}
}