3582. 为视频标题生成标签

问题

给你一个字符串 caption,表示一个视频的标题。

需要按照以下步骤 按顺序 生成一个视频的 有效标签 :

将 所有单词 组合为单个 驼峰命名字符串 ,并在前面加上 '#'。驼峰命名字符串 指的是除第一个单词外,其余单词的首字母大写,且每个单词的首字母之后的字符必须是小写。

移除 所有不是英文字母的字符,但 保留 第一个字符 '#'。

将结果 截断 为最多 100 个字符。

对 caption 执行上述操作后,返回生成的 标签 。

示例 1:
输入: caption = "Leetcode daily streak achieved"
输出: "#leetcodeDailyStreakAchieved"
解释:
除了 "leetcode" 以外的所有单词的首字母需要大写。

分析

字符串处理,用strting。如果使用常见的库函数会更简单。

法一、我的辣鸡代码

class Solution {
public:
    int c_n = 0;
    string generateTag(string caption) {
        c_n = caption.size();
        string s = "#";
        int firstIndex = 0;
        while(caption[firstIndex] == ' ') {
            firstIndex++;
        }
        for (int i = firstIndex; i < c_n; i++) {
            if (('a'<=caption[i] && caption[i] <= 'z') || ('A' <= caption[i] && caption[i] <= 'Z')) {
                if (i != firstIndex && caption[i-1] == ' ') {
                    if ('A' <= caption[i] && caption[i] <= 'Z') {
                        s += caption[i];
                    } else if ('a' <= caption[i] && caption[i] <= 'z') {
                        s += caption[i] - ('a'-'A');
                    }
                } else {
                    if ('a' <= caption[i] && caption[i] <= 'z') {
                        s += caption[i];
                    } else if ('A' <= caption[i] && caption[i] <= 'Z') {
                        s += caption[i] + ('a'-'A');
                    }
                }
            }
        }
        if (s.size() > 100) {s = s.substr(0, 100);}
        return s;
    }
};

根据测试用例,错了好几次,每次都少考虑了:

  • 字符串中可能有非字母
  • 要最后再取s的前100,而不是循环时候限制i<99(开头还有个#)
  • 开头可能有多个空格

然而,我们应该善于利用工具。

法二、学习灵神

class Solution {
public:
    string generateTag(string caption) {
        stringstream ss(caption);
        string ans = "#";
        string s;
        while (ss >> s) {
            for (auto& ch : s) {
                ch = tolower(ch);
            }
            if (ans.size() > 1) { // 不是第一个单词,首字母大写
                s[0] = toupper(s[0]);
            }
            ans += s;
            if (ans.size() >= 100) {
                ans.resize(100);
                break;
            }
        }
        return ans;
    }
};
作者:灵茶山艾府
链接:https://leetcode.cn/problems/generate-tag-for-video-caption/solutions/3700564/ku-han-shu-mo-ni-pythonjavacgo-by-endles-glg4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

stringstream流确实好用。此外,cctype的toupper和tolower也确实好用。利用工具,这题就不难。

posted @ 2025-06-15 13:54  saulstavo  阅读(18)  评论(0)    收藏  举报