CodingTour
ARTS #58

Algorithm

本周选择的算法题是:Goat Latin

规则如下:

A sentence S is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin” (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

  • If a word begins with a vowel (a, e, i, o, or u), append "ma" to the end of the word. For example, the word ‘apple’ becomes ‘applema’.

  • If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add "ma". For example, the word "goat" becomes "oatgma".

  • Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1. For example, the first word gets "a" added to the end, the second word gets "aa" added to the end and so on.

Return the final sentence representing the conversion from S to Goat Latin.

Example 1:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

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

Notes:

  • S contains only uppercase, lowercase and spaces. Exactly one space between each word.
  • 1 <= S.length <= 150.

Solution

活脱脱的 if-else 练习…

class Solution:
    def toGoatLatin(self, S: str) -> str:
        vowel = set([
            'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U', 
        ])
        ans, words_count, first_char, is_begin = [], 1, "", True
        for char in S:
            if char == " ":
                if is_begin: continue
                tail = "a" * words_count
                ans.append(f"{first_char}ma{tail}")
                is_begin, first_char, words_count = True, "", words_count + 1
            elif is_begin:
                if words_count > 1: ans.append(" ")
                if char in vowel:
                    ans.append(char)
                else:
                    first_char = char
                is_begin = False
            else:
                ans.append(char)
        if not is_begin:
            tail = "a" * words_count
            ans.append(f"{first_char}ma{tail}")
        return "".join(ans)

Review

阅读了几篇关于 Swift 内存管理的文章,篇幅有限做了单独的记录,传送门

Tip

Yet Another Swift Blog 中学习了如何实现一个简易的浏览进度展示。

JS 控制 floating-active 的添加、删除逻辑,CSS 控制样式和 transition 动画,实在太简单就不贴相关代码了。

Share

一篇关于 DNS 的用法分享,传送门