Easy
题目描述
给定一个表示视频字幕的字符串 caption。
为了生成视频的有效标签,必须按顺序执行以下操作:
将字符串中的所有单词组合成一个以 ‘#’ 为前缀的 camelCase 字符串。camelCase 字符串是除第一个单词外,所有单词的第一个字母都大写的字符串。每个单词中第一个字符之后的所有字符都必须是小写。
删除所有不是英文字母的字符,除了第一个 ‘#’。
将结果截断为最多 100 个字符。
返回对 caption 执行操作后的标签。
示例 1:
输入:caption = "Leetcode daily streak achieved"
输出:"#leetcodeDailyStreakAchieved"
解释:除了 "leetcode" 外,所有单词的第一个字母都应该大写。
示例 2:
输入:caption = "can I Go There"
输出:"#canIGoThere"
解释:除了 "can" 外,所有单词的第一个字母都应该大写。
示例 3:
输入:caption = "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
输出:"#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
解释:由于第一个单词的长度为 101,我们需要从单词中截断最后两个字母。
约束条件:
1 <= caption.length <= 150caption仅由英文字母和空格组成
解题思路
这是一道字符串处理和模拟题,需要严格按照题目要求的三个步骤来处理。
核心思路:
分割单词并转换为 camelCase:将输入字符串按空格分割成单词,第一个单词全小写,后续单词首字母大写、其余字母小写。
过滤非字母字符:由于题目输入只包含字母和空格,在分割和处理过程中自然会去除空格。
截断长度:最终结果需要截断到 100 字符以内。
实现细节:
- 遍历字符串,识别单词边界(通过空格分隔)
- 对于第一个单词,将所有字符转为小写
- 对于后续单词,首字母大写,其余小写
- 最后在结果前加上 ‘#’ 并截断到 100 字符
这种方法时间复杂度为 O(n),空间复杂度为 O(n),其中 n 是输入字符串的长度。
代码实现
class Solution {
public:
string generateTag(string caption) {
string result = "#";
bool isFirstWord = true;
for (int i = 0; i < caption.length(); i++) {
if (caption[i] == ' ') {
isFirstWord = false;
continue;
}
if (isFirstWord) {
result += tolower(caption[i]);
} else {
// Check if this is the start of a new word
if (i == 0 || caption[i-1] == ' ') {
result += toupper(caption[i]);
} else {
result += tolower(caption[i]);
}
}
}
// Truncate to 100 characters
if (result.length() > 100) {
result = result.substr(0, 100);
}
return result;
}
};
class Solution:
def generateTag(self, caption: str) -> str:
result = "#"
is_first_word = True
for i, char in enumerate(caption):
if char == ' ':
is_first_word = False
continue
if is_first_word:
result += char.lower()
else:
# Check if this is the start of a new word
if i == 0 or caption[i-1] == ' ':
result += char.upper()
else:
result += char.lower()
# Truncate to 100 characters
return result[:100]
public class Solution {
public string GenerateTag(string caption) {
StringBuilder result = new StringBuilder("#");
bool isFirstWord = true;
for (int i = 0; i < caption.Length; i++) {
if (caption[i] == ' ') {
isFirstWord = false;
continue;
}
if (isFirstWord) {
result.Append(char.ToLower(caption[i]));
} else {
// Check if this is the start of a new word
if (i == 0 || caption[i-1] == ' ') {
result.Append(char.ToUpper(caption[i]));
} else {
result.Append(char.ToLower(caption[i]));
}
}
}
// Truncate to 100 characters
string finalResult = result.ToString();
return finalResult.Length > 100 ? finalResult.Substring(0, 100) : finalResult;
}
}
var generateTag = function(caption) {
let result = "#";
let isFirstWord = true;
for (let i = 0; i < caption.length; i++) {
if (caption[i]
复杂度分析
| 项目 | 复杂度 |
|---|---|
| 时间复杂度 | O(n) |
| 空间复杂度 | O(n) |
其中 n 是输入字符串 caption 的长度。时间复杂度为 O(n) 是因为需要遍历整个字符串一次;空间复杂度为 O(n) 是因为需要存储结果字符串。