201412-3 命令行选项

1、用两个布尔数组来存储选项及其是否带参

2、遍历命令行的时候,用正则匹配每个字符是否匹配选项或参数的规则,然后查看是否存在该选项。出现的选项及其参数用TreeMap存储,因为treemap可以对key进行排序,正好是题目要求的输出。

奉上java满分代码

import java.util.*;

public class Main {

    public static void main(String[] args) {
        boolean[] options = new boolean[97 + 26];
        boolean[] params = new boolean[97 + 26];

        Scanner scanner = new Scanner(System.in);
        String firstLine = scanner.nextLine();
        char lastChar = 0;
        for (int i = 0; i < firstLine.length(); i++) {
            char ch = firstLine.charAt(i);
            if (ch == ':') {
                params[lastChar] = true;
            } else {
                options[ch] = true;
                lastChar = ch;
            }
        }
        int n = Integer.parseInt(scanner.nextLine());
        List<String> commands = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            commands.add(scanner.nextLine());
        }
        scanner.close();

        for (int j = 0; j < n; j++) {
            String command = commands.get(j);
            String[] data = command.split(" ");
            TreeMap<Character, String> treeMap = new TreeMap<>();
            boolean isParam = false;
            char lastOption = 0;
            for (int i = 1; i < data.length; i++) {
                String str = data[i];
                if (isParam) {
                    if (str.matches("[a-z0-9\\-]+")) {
                        treeMap.put(lastOption, str);
                    }
                    isParam = false;
                } else if (str.matches("\\-[a-z]") && options[str.charAt(1)]) {
                    char option = str.charAt(1);
                    if(params[option]){
                        isParam = true;
                    } else{
                        isParam = false;
                        treeMap.put(option, "");
                    }
                    lastOption = option;
                } else {
                    break;
                }
            }

            StringBuffer stringBuffer = new StringBuffer(String.format("Case %d: ", j + 1));
            for(Iterator<Character> iterator = treeMap.keySet().iterator(); iterator.hasNext();){
                char option = iterator.next();
                stringBuffer.append("-" + option + " ");
                String val = treeMap.get(option);
                if(val.length() > 0){
                    stringBuffer.append(val + " ");
                }
            }
            System.out.println(stringBuffer.toString());
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_23934649/article/details/84844955
今日推荐