今日头条---后台开发笔试题

第一题:

简化Unix风格的路径:

实例:

输入:/home/

输出:/home

实例2:

输入:/a/./b/../../c/

输出:/c

分析:(参考自:https://blog.csdn.net/qq_28618765/article/details/78013580?utm_source=copy

“..”表示返回路径的上级目录(如果当前是根目录则不处理),“.”表示当前目录。

使用栈来记录路径名。在处理字符串路径的过程中,遵循以下条件:

(1)重复连续的“/”,只需处理一个即可,即跳过重复连续出现的多个“/”;

(2)如果路径名不为“.”或“..”,将记录的字符串入栈;

(3)如果路径名是“..”且栈不为空,则需要出栈,否则无需处理。

在遍历完字符串之后,逐个取出栈中元素,用“/”分隔并拼接起来,注意:取出的元素是从后往前进行拼接的。

def test(path):
    pathlist=path.split('/')
    catch=[]
    result=''
    for data in pathlist:
        if data not in ["",".",".."]:
            catch.append(data)
        if '..'==data and catch:
            catch.pop(-1)
    if catch==[]:
        return "/"
    for data in catch:
        result=result+"/"+data+""
    return result
if __name__=='__main__':
    path=raw_input('')
    result=test(path)
    print result

运行结果:

运行AC 

第二题:

得出字符串前缀,来唯一标识该字符串;

if __name__=='__main__':
    n=int(raw_input())
    strlist=[]
    result=[]
    t=[]
    flag = 0
    for i in range(n):
        catch=raw_input()
        strlist.append(catch)
    for i in range(0,len(strlist)):
        result=[]
        for j in range(0,len(strlist)):
            for y in range(0,len(strlist[i])+1):
                if i!=j:
                    item=strlist[i][:y]
                    if strlist[j].find(item)!=0 :
                        result.append(strlist[i][:y])
                        result.sort()
                        break
        print result.pop()

# #
# 5
# bytedance
# toutiaohao
# toutiaoapp
# iesaweme
# iestiktok
# b
# toutiaoh
# toutiaoa
# iesa
# iest
# #

运行结果为:

结果:

但:输入一个字符串是会出错

运行20%;运行时间超时。。。。。。。。

 

 

修改

if __name__=='__main__':
    n=int(raw_input())
    strlist=[]
    result=[]
    t=[]
    flag = 0
    for i in range(n):
        catch=raw_input()
        strlist.append(catch)
    for i in range(0,len(strlist)):
        result=[]
        result.append(strlist[i][0])
        for j in range(0,len(strlist)):
            for y in range(0,len(strlist[i])+1):
                if i!=j:
                    item=strlist[i][:y]
                    if strlist[j].find(item)!=0 :
                        result.append(strlist[i][:y])
                        break
        result.sort()
        print result.pop()

运行结果为:

欢迎大佬指点!!!!!!!!!!!!!

实验知识点:

list分割:

知识点:

(1)list中的pop()

参考链接:http://www.runoob.com/python/att-list-pop.html

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

语法

pop()方法语法:

list.pop([index=-1])

参数

  • obj -- 可选参数,要移除列表元素的索引值,不能超过列表总长度,默认为 index=-1,删除最后一个列表值。

返回值

该方法返回从列表中移除的元素对象。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值