编程题例题

# 1.找出字符串数组中最长的公共字符前缀
# test_strs1 = ["flower", "flow", "flight"]
# 结果为:fl
# test_strs2 = ["dog", "rececar", "car"]
# 结果为空

def longestCommonPrefix(strs):
    if strs is None:
        return ""
    prefix = strs[0]
    for i in range(1, len(strs)):
        if strs[i] is None:
            return ""
        while prefix and not strs[i].startswith(prefix):
            prefix = prefix[:-1]
    return prefix


test_strs1 = ["flower", "flow", "flight"]
print(longestCommonPrefix(test_strs1))
test_strs2 = ["dog", "rececar", "car"]
print(longestCommonPrefix(test_strs2))

# 2.给定由若干单词组成的字符串,单词前后用一些空格字符隔开,返回字符串中最长单词的长度
# s = "fly me to the moon"
# 结果为:4

def length_longest_word(s):
    words = s.split()   # 以空格切分
    max_length = 0
    for word in words:
        if len(word) > max_length:
            max_length = len(word)
    return max_length

s_test = " fly me to the moon "
print(length_longest_word(s_test))
"""
3.给一个文件,名称为a.txt,文件有2行内容:
bb cc dd aa
zz ee ff yy
要求读取该文件,并输出zz yy ff ee dd cc bb aa
"""


# 打开文件
with open('a.txt', 'r') as file:
    lines = file.readlines()

list_words = []

for line in lines:
    words = line.strip().split()
    list_words += words
    list_words.sort()
print(' '.join(list_words[::-1]))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值