【Leetcode_总结】824. 山羊拉丁文 - python

Q:

给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。

我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。

山羊拉丁文的规则如下:

  • 如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"
    例如,单词"apple"变为"applema"
  • 如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"
    例如,单词"goat"变为"oatgma"
  • 根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。
    例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。

返回将 S 转换为山羊拉丁文后的句子。

示例 1:

输入: "I speak Goat Latin"
输出: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

示例 2:

输入: "The quick brown fox jumped over the lazy dog"
输出: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

思路:

暴力求解

class Solution:
    def toGoatLatin(self, S):
        """
        :type S: str
        :rtype: str
        """
        vowel = ['a','e','i','o','u']
        temp = S.split()
        for i in range(len(temp)):
            j = i + 1
            if temp[i][0].lower() in vowel:
                temp[i] = temp[i]+'ma'
                while j > 0:
                    temp[i] += 'a'
                    j -= 1
            else:
                temp[i] = temp[i][1:len(temp[i])] + temp[i][0] + 'ma'
                while j > 0:
                    temp[i] += 'a'
                    j -= 1
        return " ".join(temp).lstrip(' ')

 效率不高,由于循环太多

改进:字符串是可以使用乘法相加的,避免使用循环

class Solution:
    def toGoatLatin(self, S):
        """
        :type S: str
        :rtype: str
        """
        vowel = ['a','e','i','o','u']
        temp = S.split()
        for i in range(len(temp)):
            if temp[i][0].lower() in vowel:
                temp[i] = temp[i]+'ma' + 'a' * (i+1)
            else:
                temp[i] = temp[i][1:] + temp[i][0] + 'ma'+ 'a' * (i+1)
        return " ".join(temp).lstrip(' ')

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值