Sponsored
Sponsored
This approach involves iterating through each name in the list, transforming the name so that the first letter is uppercase and the rest are lowercase. This is a common string manipulation problem that can be solved using built-in string functions in most programming languages.
Time Complexity: O(n) for each name, where n is the length of the name.
Space Complexity: O(1) since we modify the names in place.
1#include <iostream>
2#include <algorithm>
3#include <cctype>
4#include <vector>
5
6void formatName(std::string &name) {
7 if (name.empty()) return;
8 name[0] = toupper(name[0]);
9 std::transform(name.begin() + 1, name.end(), name.begin() + 1, ::tolower);
10}
11
12int main() {
13 // Example usage
14 std::vector<std::pair<int, std::string>> users = {{1, "aLice"}, {2, "bOB"}};
15
16 std::cout << "+---------+-------+\n";
17 std::cout << "| user_id | name |\n";
18 std::cout << "+---------+-------+\n";
19 for (auto &user : users) {
20 formatName(user.second);
21 std::cout << "| " << user.first << " | " << user.second << " |\n";
22 }
23 std::cout << "+---------+-------+\n";
24
25 return 0;
26}
In C++, the transform
algorithm is used in conjunction with tolower
to convert the remaining characters to lowercase. The first character is handled separately to ensure it's uppercase.
This approach applies regular expressions to locate patterns that match the criteria and replace them with the desired format. This leverages the pattern matching capability of regex to achieve the transformation in fewer lines of code.
Time Complexity: O(n) for each name due to regex matching and replacement, where n is the length of the name.
Space Complexity: O(n) for storing the modified strings.
1import re
2
3def format_names(users
In this Python solution, the regex (\w)(\w*)
captures the first character and the remainder of the string separately. The lambda function then applies the uppercase and lowercase transformations in one substitution step.