1. 程式人生 > >201412-3 命令列選項

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());
        }

    }
}