LeetCode2129. Capitalize the Title

一、题目

You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:

If the length of the word is 1 or 2 letters, change all letters to lowercase.
Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title.

Example 1:

Input: title = “capiTalIze tHe titLe”
Output: “Capitalize The Title”
Explanation:
Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.
Example 2:

Input: title = “First leTTeR of EACH Word”
Output: “First Letter of Each Word”
Explanation:
The word “of” has length 2, so it is all lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.
Example 3:

Input: title = “i lOve leetcode”
Output: “i Love Leetcode”
Explanation:
The word “i” has length 1, so it is lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

Constraints:

1 <= title.length <= 100
title consists of words separated by a single space without any leading or trailing spaces.
Each word consists of uppercase and lowercase English letters and is non-empty.

二、题解

class Solution {
public:
    string capitalizeTitle(string title) {
        istringstream str(title);
        string res;
	    string out;
        while(str >> out){
            int n = out.size();
            if(n < 3){
                for(int i = 0;i < n;i++){
                    res += tolower(out[i]);
                }
                res += " ";
            }
            else{
                res += toupper(out[0]);
                for(int i = 1;i < n;i++){
                    res += tolower(out[i]);
                }
                res += " ";
            }
        }
        res.pop_back();
        return res;
    }
};
  • 20
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值