CCF-201604-3-路径解析

这题一开始我是看不懂的,不过慢慢看懂后,发现原来很简单。题目叫我们正规化每个路径。其实就是模拟路径的走向,最后生成绝对路径。题目输入的当前目录其实对相对路径才有用。

具体思路

  1. 当前目录按 ‘/’ 斜杆分割成列表。判断输入的路径是不是绝对路径,是绝对路径就得当前目录改为根目录。(具体就是把当前目录清空)
  2. 把输入的路径按 ‘/’ 斜杆分割成列表,从左到右遍历这个列表。
    1)遇到是空字符和‘.’就忽略(这就可以解决重复分号和单点的情况)
    2)遇到两个点,就返回上一级,具体到操作就是删除当前目录的最后一个元素
    3)遇到正常字符串(目录或文件)就在当前目录后面加上这个元素

细节:
输入为空路径的时候是打印当前目录

python代码

p = int(input())
paths = []
cur_path = input()
for i in range(p):
    path = input().split('/')
    stack = [] if path[0] == '' and len(path) > 1 else cur_path.split('/')[1:]
    for e in path:
        if e == '..' and stack:
            stack.pop()
        if e != '.' and e != '..' and e:
            stack.append(e)
    print('/' + '/'.join(stack) if stack else '/')

你可能感兴趣的:(CCF)