1.문제
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:
- If the length of the word is 1 or 2 letters, change all letters to lowercase.
- Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title.
1개 이상의 단어들로 이뤄진 문자열인 title이 주어질 때 단어들은 하나의 공백으로 구분되어있다고 한다.
title 의 단어들을 다음 규칙들을 적용하여 변환하는 문제이다.
- 만약 단어의 길이가 2 이하이면 모든 철자는 소문자여야한다.
- 만약 단어의 길이가 3 이상이면 단어의 제일 앞 철자만 대문자이어야 한다.
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:
- 1 <= title.length <= 100
- title consists of words separated by a single space without any leading or trailing spaces.
- Each word consists of uppercase and lowercase English letters and is non-empty.
2.풀이
- 각 단어들을 반복문을 돌면서 길이에 따라 변환해준다.
/**
* @param {string} title
* @return {string}
*/
const capitalizeTitle = function (title) {
title = title.split(" ");
for (let i = 0; i < title.length; i++) {
if (title[i].length <= 2) {
// 단어의 길이가 2 이하이면 소문자로 바꾼다
title[i] = title[i].toLowerCase();
} else {
// 단어의 길이가 3이상이면 앞 철자만 대문자로 바꿔준다.
title[i] = title[i].toLowerCase();
let temp = title[i].split("");
temp.shift();
temp.unshift(title[i][0].toUpperCase());
title[i] = temp.join("");
}
}
return title.join(" ");
};
3.결과
