LeetCode-in-Java

2129. Capitalize the Title

Easy

You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:

Return the capitalized title.

Example 1:

Input: title = “capiTalIze tHe titLe”

Output: “Capitalize The Title”

Explanation: Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.

Example 2:

Input: title = “First leTTeR of EACH Word”

Output: “First Letter of Each Word”

Explanation:

The word “of” has length 2, so it is all lowercase.

The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

Example 3:

Input: title = “i lOve leetcode”

Output: “i Love Leetcode”

Explanation:

The word “i” has length 1, so it is lowercase.

The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

Constraints:

Solution

public class Solution {
    public String capitalizeTitle(String title) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        int j = 0;
        while (i < title.length()) {
            while (j < title.length() && title.charAt(j) != ' ') {
                sb.append(Character.toLowerCase(title.charAt(j)));
                j++;
            }
            int len = j - i;
            if (len > 2) {
                sb.setCharAt(i, Character.toUpperCase(title.charAt(i)));
            }
            if (j == title.length()) {
                break;
            }
            sb.append(title.charAt(j));
            i = ++j;
        }
        return sb.toString();
    }
}