๋ฌธ์ ๋งํฌ
Unique Morse Code Words - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
์ฃผ์ด์ง ๋ชจ์ค ๊ธฐํธ ๋ฐฐ์ด์ ์ํ๋ฒณ ์๋ฌธ์์ ๋ฒํธ์ ์ผ์นํ๋ค. ( a === ".-", b === "-..." ... )
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]โ
๋จ์ด๊ฐ ์ฃผ์ด์ง๋, ํด๋น ๋จ์ด์ ๋ชจ์ค๊ธฐํธ๋ฅผ ๊ตฌํด ๋ฐฐ์ด์ ์ ์ฅํ๊ณ ์ค๋ณต๋์ง ์๋ ๋ชจ์ค๊ธฐํธ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
์ ๊ทผ ๋ฐฉ๋ฒ
์ํ๋ฒณ ์๋ฌธ์์ ๋ชจ์ค ๊ธฐํธ ๋ฒํธ๊ฐ ๊ฐ์ผ๋ฏ๋ก charCodeAt()์ ํตํด ์์คํค ์ฝ๋ ๋ฒํธ๋ก ์ ๊ทผํ๋ ๋ฐฉ์์ ์ฑํํ์๋ค.
const morseCodeArr= [] words.forEach(word => { let morseCode = ""; for(let char of word){ morseCode += morseSign[char.charCodeAt() - 97] } morseCodeArr.push(morseCode) })โ
๋น ๋ฐฐ์ด์ ํ๋ ์์ฑํ๊ณ ๋ชจ๋ ๋จ์ด๋ฅผ ์ํํ๋ฉฐ ๊ฐ ๋จ์ด์ ๋ฌธ์์ ์์คํค ์ฝ๋๋ฅผ ๊ตฌํด - 97์ ํ๋ค.
( 'a'์ ์์คํค ์ฝ๋๋ 97์ด๋ฏ๋ก ๋ชจ๋ ์์ด ์๋ฌธ์์ -97์ ํ๋ฉด 0~26๊น์ง์ ๊ฐ์ ์ป์ ์ ์๋ค.)
๊ทธ๋ ๊ฒ ๋น๋ฐฐ์ด์ ๋ชจ๋ ๋ชจ์ค ๊ธฐํธ๋ฅผ ์ ์ฅํ๊ณ ์ค๋ณต์ ์ ๊ฑฐํ๋ฉด ์ ๋ต์ ๊ตฌํ ์ ์๋ค.
/**
* @param {string[]} words
* @return {number}
*/
var uniqueMorseRepresentations = function(words) {
const morseSign = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."];
const morseCodeArr= []
words.forEach(word => {
let morseCode = "";
for(let char of word){
morseCode += morseSign[char.charCodeAt() - 97]
}
morseCodeArr.push(morseCode)
})
return (new Set(morseCodeArr)).size
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Rotate Image (0) | 2022.08.30 |
---|---|
[LeetCode] Reduce Array Size to The Half (0) | 2022.08.18 |
[LeetCode] Combination Sum IV (0) | 2022.08.05 |
[LeetCode] My Calendar I (0) | 2022.08.03 |
[LeetCode] Kth Smallest Element In A Sorted Matrix (0) | 2022.08.02 |