LeetCode - Algorithms - 2129. Capitalize the Title

Problem

2129. Capitalize the Title

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public:
string capitalizeTitle(string title) {
int len = title.length();
int start = 0;
int end = 0;
for(int i = 0; i < len; i++) {
if (title.at(i) == ' ') {
end = i-1;
if (end - start <= 1) {
for(int j=start; j<=end; j++)
title.at(j) = tolower(title.at(j));
}
else {
title.at(start) = toupper(title.at(start));
for(int j=start+1; j<=end; j++)
title.at(j) = tolower(title.at(j));
}
start = i + 1;
}
if (i == len-1) {
end = len -1;
if (end - start <= 1) {
for(int j=start; j<=end; j++)
title.at(j) = tolower(title.at(j));
}
else {
title.at(start) = toupper(title.at(start));
for(int j=start+1; j<=end; j++)
title.at(j) = tolower(title.at(j));
}
}
}
return title;
}
};

Submission Detail

  • 200 / 200 test cases passed.
  • Runtime: 3 ms, faster than 69.22% of C++ online submissions for Capitalize the Title.
  • Memory Usage: 6.3 MB, less than 74.15% of C++ online submissions for Capitalize the Title.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public String capitalizeTitle(String title) {
String[] arr = title.split(" ");
for(int i=0; i < arr.length; i++) {
if (arr[i].length() <= 2)
arr[i] = arr[i].toLowerCase();
else {
char[] charArr = arr[i].toCharArray();
charArr[0] = Character.toUpperCase(charArr[0]);
for(int j=1; j < charArr.length; j++)
charArr[j] = Character.toLowerCase(charArr[j] );
arr[i] = new String(charArr);
}
}
return String.join(" ", arr);
}
}

Submission Detail

  • 200 / 200 test cases passed.
  • Runtime: 10 ms, faster than 47.35% of Java online submissions for Capitalize the Title.
  • Memory Usage: 42.8 MB, less than 67.17% of Java online submissions for Capitalize the Title.