[Leetcode] 704. Make The String Great โ
#๋ฌธ์์ด
Problem โ
๋ฌธ์์ด์ด ์ฃผ์ด์ง๋ ์๋ก ์ธ์ ํ ๋ฌธ์๊ฐ ๋๋ฌธ์์ ์๋ฌธ์์ด๋ฉด์ ๊ฐ์ ์ํ๋ฒณ์ด๋ฉด ์ ๊ฑฐํ๋ฉด์ ์ต์ข ๋ฌธ์์ด์ ์ถ๋ ฅํ๋ ๋ฌธ์
ex) leEeetcode => leetcode ex) abBAcC => "" ex) "kkdsFuqUfSDKK" => "kkdsFuqUfSDKK"
Solution โ
- ๋ฌธ์์ด์ ์ํ๊ฐ๋ฅํ๊ฒ ๋ง๋ ๋ค.
- ๊ฐ์ฐ๊ธฐ๋ฅผ ์ด์ฉํ์ฌ ๋ฌธ์์ด์ ์์ฑํ๋ค.
- ์ฃผ์ด์ง c์ ๊ฐ์ฐ๊ธฐ์ ๋ง์ง๋ง ๋ฌธ์๊ฐ ์๋ก ๋์๋ฌธ์์ธ์ง ์กฐ๊ฑด์ ํตํด ๊ตฌ๋ณํ๋ค.
- ๊ฐ์ ์ํ๋ฒณ์ธ์ง ํ์ธํ๋ค.
- ์ ์กฐ๊ฑด์ ์ผ์นํ๋ฉด ๊ฐ์ฐ๊ธฐ์ ๋ง์ง๋ง ๋ฌธ์๋ฅผ ์ ๊ฑฐํ๋ค.
- ์ ์กฐ๊ฑด์ ์ผ์นํ์ง์์ผ๋ฉด ๊ฐ์ฐ๊ธฐ์ c(๋ฌธ์)๋ฅผ ์ถ๊ฐํ๋ค.
TS Code โ
ts
function makeGood(s: string): string {
const isUpperCase = (c: string) => c === c.toUpperCase()
const isLowerCase = (c: string) => c === c.toLowerCase()
return Array.from(s).reduce((acc: string, c: string, i: number) => {
const lastChar = acc[acc.length - 1]
if (!acc) return c
if (((isUpperCase(lastChar) && isLowerCase(c)) || (isUpperCase(c) && isLowerCase(lastChar))) && c.toUpperCase() === lastChar.toUpperCase()) return acc.slice(0, -1)
return acc + c
})
}