The "Fix Product Name Format" problem asks you to reformat a given product name string so that it follows a specific capitalization rule. The rules are:
For example, given the input string " aPpLe iPhOne 13 pro "
, the output should be "Apple Iphone 13 Pro"
.
The key constraints are:
When approaching this problem, the first thought might be to manually scan each character and capitalize letters as needed. However, this can become cumbersome and error-prone, especially when dealing with multiple spaces and mixed cases.
A more systematic approach is to:
This leverages built-in string manipulation functions, making the code cleaner and more reliable. The main challenge is handling the capitalization correctly and ensuring that all extra spaces are removed.
Let's break down the solution step by step:
capitalize()
in Python, or by combining toUpperCase()
and toLowerCase()
in other languages.
This approach is efficient and easy to understand. We use built-in functions because they are optimized and less error-prone than manual character manipulation.
Let's walk through the example input: " aPpLe iPhOne 13 pro "
["aPpLe", "iPhOne", "13", "pro"]
"Apple Iphone 13 Pro"
This matches the expected output.
Brute-force Approach:
Both approaches are linear in time and space, but using built-in functions is more concise and less error-prone.
In summary, the problem is about normalizing the capitalization and spacing of a product name string. The most elegant solution leverages string splitting, word-wise capitalization, and joining, all using built-in functions. This approach is both efficient and readable, making it ideal for production code. The key insight is to break the problem into manageable steps and use the right tools for each part.
def fixProductName(name: str) -> str:
words = name.strip().split()
fixed_words = [w.capitalize() for w in words]
return ' '.join(fixed_words)
#include <string>
#include <vector>
#include <sstream>
#include <cctype>
using namespace std;
string fixProductName(string name) {
istringstream iss(name);
string word, result;
while (iss >> word) {
if (!word.empty()) {
word[0] = toupper(word[0]);
for (int i = 1; i < word.size(); ++i) {
word[i] = tolower(word[i]);
}
if (!result.empty()) result += " ";
result += word;
}
}
return result;
}
public class Solution {
public String fixProductName(String name) {
String[] words = name.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; ++i) {
if (words[i].length() == 0) continue;
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1) {
sb.append(words[i].substring(1).toLowerCase());
}
if (i != words.length - 1) sb.append(" ");
}
return sb.toString();
}
}
function fixProductName(name) {
return name.trim().split(/\s+/).map(word =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
).join(' ');
}