当前位置:网站首页>Capitalize the title of leetcode simple question

Capitalize the title of leetcode simple question

2022-07-06 15:04:00 ·Starry Sea

subject

Give you a string title , It consists of a single space connecting one or more words , Each word contains only English letters . Please put the first letter of each word according to the following rules Capitalization :
If the length of the word is 1 perhaps 2 , All letters in lowercase .
otherwise , Capitalize the first letter of the word , The remaining letters become lowercase .
Please return After capitalization Of title .
Example 1:
Input :title = “capiTalIze tHe titLe”
Output :“Capitalize The Title”
explain :
Because all words are at least 3 , Capitalize each word , The remaining letters become lowercase .
Example 2:
Input :title = “First leTTeR of EACH Word”
Output :“First Letter of Each Word”
explain :
word “of” The length is 2 , So it stays completely lowercase .
Other words are at least... Long 3 , So other words are capitalized , The remaining letters are lowercase .
Example 3:
Input :title = “i lOve leetcode”
Output :“i Love Leetcode”
explain :
word “i” The length is 1 , So it keeps lowercase .
Other words are at least... Long 3 , So other words are capitalized , The remaining letters are lowercase .
Tips :
1 <= title.length <= 100
title Words separated by a single space , And does not contain any leading or suffix spaces .
Each word consists of uppercase and lowercase letters , And are Non empty Of .
source : Power button (LeetCode)

Their thinking

   about title Every word in , Replace case by condition .

class Solution:
    def capitalizeTitle(self, title: str) -> str:
        def change(matched):
            word=matched.group('word')
            return word.lower() if len(word)<3 else word[0].upper()+word[1:].lower()
        return re.sub('(?P<word>\S+)',change,title) # Replace letters according to rules 

 Insert picture description here

原网站

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131327152896.html