题目

The Hashtag Generator

Hashtag生成器

描述

The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!

Here's the deal:

  • It must start with a hashtag (#).
  • All words must have their first letter capitalized.
  • If the final result is longer than 140 chars it must return false.
  • If the input or the result is an empty string it must return false.

营销团队花了太多的时间输入标签。

让我们用我们自己的标签生成器来帮助他们!

交易如下:

  • 它必须以hashtag(#)开头。
  • 所有单词的首字母都必须大写。
  • 如果最终结果超过140个字符,则必须返回false。
  • 如果输入或结果为空字符串,则必须返回false。

例子

" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false

思路

这个题和我们之前讲的将字符串转换为驼峰大小写类似,本题也是和驼峰转换一样的,但是和之前不一样的是,也是本题的注意点:

  1. pre不是"-"和"_"这两个字符了,而是" "空格,这里需要修改
  2. 这里需要处理首字母大写,之前是不需要修改的
  3. 本题会出现单词中间出现大写字母的情况,需要处理成小写字母
  4. 这里有长度140的限制,最后做一些判断即可
  5. 如果字符串长度为空的情况,返回false

完整代码

def generate_hashtag(s):
    #your code here
    # 创建一个列表,用来保存结果
    result = ["#"]
    # 创建一个值用来保存上一个字符
    pre = ""
    # 记录出现的第一个字母,大写
    flag = 0
    # 如果s是空的,那么就返回空
    if s == "":
        return False
    for i in range(len(s)):
        # 如果pre是“ ”就当前的字母装换为大写,其他的自动添加
        if s[i] != " ":
            # 出现第一个字母时大写,以及每个单词的首字母大写
            if pre == " " or flag == 0:
                result.append(s[i].upper())
                flag = 1
            # 当前一个是字母,但是,当前是大写时,这里要小写。
            elif pre.isalpha() and s[i].isupper():
                result.append(s[i].lower())
            else:
                result.append(s[i])
        pre = s[i]
    if len(result) > 140:
        return False
    return ''.join(result)