【面试题】去除字符串中的空格

用python作答下题,不可使用strip和re:给定一个字符串S,去除S首尾的空格,并将字符串中间连续的多个空格替换为1个空格,返回处理后的字符串。

GPT4作答

def remove_extra_spaces(s):
    # 初始化一个空列表来存储单词
    words = []
    # 初始化一个空字符串来存储当前的单词
    word = ''
    # 遍历字符串中的每个字符
    for c in s:
        # 如果当前字符不是空格,将其添加到当前单词
        if c != ' ':
            word += c
        # 如果当前字符是空格,且当前单词不为空,将当前单词添加到单词列表,并清空当前单词
        elif word:
            words.append(word)
            word = ''
    # 如果最后一个单词不为空,将其添加到单词列表
    if word:
        words.append(word)
    # 使用单个空格连接单词列表,得到处理后的字符串
    return ' '.join(words)

# 测试
s = '  hello   world  '
result = remove_extra_spaces(s)
print(result)  # 输出:'hello world'

在这个函数中,我们首先初始化了一个空列表words来存储单词,以及一个空字符串word来存储当前的单词。然后,我们遍历字符串中的每个字符。如果当前字符不是空格,我们将其添加到当前单词。如果当前字符是空格,且当前单词不为空,我们将当前单词添加到单词列表,并清空当前单词。最后,我们使用单个空格连接单词列表,得到处理后的字符串。

我的答案

def my_strip(s):
    if not s:
        return ''
    start = 0
    end = len(s) - 1
    while start <= end and s[start] == ' ':
        start += 1
    while end >= start and s[end] == ' ':
        end -= 1
    return s[start:end+1]


def normilize(s):
    s=my_strip(s)
    if not s:
        return ''
    i=1
    n=len(s)
    res=''
    while i<n-1:
        if s[i]!=' ':
            res+=s[i]
        else:
            if s[i+1]!=' ':
                res+=' '

        i+=1
    return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值