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.
1import java.util.Arrays;
2import java.util.List;
3
4public class Main {
5 public static void formatName(String[] names) {
6 for (int i = 0; i < names.length; i++) {
7 if (names[i].length() == 0) continue;
8 String formattedName = names[i].substring(0, 1).toUpperCase() + names[i].substring(1).toLowerCase();
9 names[i] = formattedName;
10 }
11 }
12
13 public static void main(String[] args) {
14 String[] names = {"aLice", "bOB"};
15 int[] user_ids = {1, 2};
16
17 formatName(names);
18 System.out.println("+---------+-------+");
19 System.out.println("| user_id | name |");
20 System.out.println("+---------+-------+");
21 for (int i = 0; i < user_ids.length; i++) {
22 System.out.format("| %d | %s |\n", user_ids[i], names[i]);
23 }
24 System.out.println("+---------+-------+");
25 }
26}
Java provides toUpperCase()
and toLowerCase()
methods for string manipulation. We capitalize the first character and lowercase the others by slicing the string appropriately.
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.
1function formatNames(users) {
2 return
JavaScript's replace
function, allied with capturing groups in the regex ^(\w)(\w*)
, helps modify the string efficiently. This approach makes it easier to manage complex string manipulation tasks.