Generate Tag for Video Caption Problem
#3582
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3582.
You are given a string caption representing the caption for a video.
The following actions must be performed in order to generate a valid tag for the video:
- Combine all words in the string into a single camelCase string prefixed with
'#'. A camelCase string is one where the first letter of all words except the first one is capitalized. All characters after the first character in each word must be lowercase. - Remove all characters that are not an English letter, except the first
'#'. - Truncate the result to a maximum of 100 characters.
Return the tag after performing the actions on caption.
Example 1:
Input: caption = "Leetcode daily streak achieved"
Output: "#leetcodeDailyStreakAchieved"
Explanation:
The first letter for all words except "leetcode" should be capitalized.
Example 2:
Input: caption = "can I Go There"
Output: "#canIGoThere"
Explanation:
The first letter for all words except "can" should be capitalized.
Example 3:
Input: caption = "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
Output: "#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
Explanation:
Since the first word has length 101, we need to truncate the last two letters from the word.
Constraints:
1 <= caption.length <= 150captionconsists only of English letters and' '.
Solution
Approach: Simulation
Split the caption into words (ignoring extra spaces). Lowercase the first word; for each later word, uppercase its first letter and lowercase the rest. Join the words, put # in front, and cut the result to its first 100 characters.
Complexity: O(n) time and O(n) space, where n is the length of the caption.
class Solution:
def generateTag(self, caption: str) -> str:
words = [s.capitalize() for s in caption.split()]
if words:
words[0] = words[0].lower()
return "#" + "".join(words)[:99]