CCF-201403-3-命令行选项

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AivenZhong/article/details/83957956

第三题一如既往的是模拟题,这次模拟解释命令行。做第三题的心态就是:不要被题目吓到,不用急,慢慢看完就好,最后注意细节。这一题规则很清晰,难度适中。

题目大意
给一个格式化字符串(每个字母是一个选项),再给出几个命令行,看每个命令行里面哪些选项符合就输出哪些,遇到不符合的就结束分析

思路

  1. 先把选项分类好。一种是不带参数类型(列表存储),另一种是带参数类型(存储数据结构因人而异,python用字典,java用map,反正要可以存储带参数选项的参数)
  2. 处理命令行,一个个选项看,如果该选项是带参数类型的,读取后面的参数,更新选项的参数值,把参数加入ans(答案列表,存储不重复的选项);如果选项是不带参数类型的,看是否已经加入过ans,没有就加入。
  3. 最后遍历ans,如果选项是带参数类型输出选项同时输出参数,不带参数类型只输出选项
  4. 细节:注意带参数类型的参数,组成字符可以是符号‘-’,字母和数字,还有处理格式字符串和命令行选项的时候,注意不要溢出。
format_str = input()
no_arg_opt = []
has_arg_opt = {}

# 处理格式字符串,分类
idx = 0
while idx < len(format_str):
    if idx + 1 < len(format_str) and format_str[idx + 1] == ':':
        has_arg_opt[format_str[idx]] = ''
        idx += 2
    else:
        no_arg_opt.append(format_str[idx])
        idx += 1

# 处理命令行
n = int(input())
for i in range(n):
    line = input().split()[1:]
    ans = []  # 正确匹配到的操作
    idx = 0
    while idx < len(line):
        op_or_arg = line[idx]
        # 如果是操作
        if op_or_arg[0] == '-':
            # 带参数的操作
            if op_or_arg[1] in has_arg_opt:
                # 找到参数,更新字典,加入ans
                if idx + 1 < len(line):
                    has_arg_opt[op_or_arg[1]] = line[idx + 1]
                    if op_or_arg[1] not in ans:
                        ans.append(op_or_arg[1])
                idx += 2

            # 不带参数的操作,不重复项才加入ans
            else:
                if op_or_arg[1] in no_arg_opt:
                    if op_or_arg[1] not in ans:
                        ans.append(op_or_arg[1])
                else:
                    break
                idx += 1
        # 不是操作,结束分析
        else:
            break

    # 处理ans,按升序输出操作如果是带参数的操作,输出后面带参数
    print('Case {}: '.format(i + 1), end='')
    ans = sorted(ans)
    for op in ans:
        if op in has_arg_opt:
            print('-{} {}'.format(op, has_arg_opt[op]), end=' ')
        else:
            print('-{}'.format(op), end=' ')
    print()

# 测试用例
# albw:x
# 4
# ls -a -l -a documents -b
# ls
# ls -w 10 -x -w 15
# ls -a -b -c -d -e -l

# albxw:
# 4
# ls -a -l -a documents -b
# ls
# ls -w 10 -x -w -15 -w
# ls -a -b -c -d -e -l

猜你喜欢

转载自blog.csdn.net/AivenZhong/article/details/83957956