๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 2390 - Removing Stars From a String (Medium)

by HandHand 2023. 4. 24.

 

๐Ÿ’ก ๋ฌธ์ œ

LeetCode - 2390๋ฒˆ

 

๐ŸŽฏ ํ’€์ด ๊ณผ์ •

๋ณ„ํ‘œ (*)๋ฅผ ํฌํ•จํ•œ ๋ฌธ์ž์—ด s ์—์„œ ๋‹ค์Œ ๊ทœ์น™์— ๋”ฐ๋ผ ๋ชจ๋“  ๋ณ„ํ‘œ๊ฐ€ ์ œ๊ฑฐ๋œ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ณ„ํ‘œ๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ํ•ด๋‹น ๋ณ„ํ‘œ๋ณด๋‹ค ์•ž์ชฝ์— ์œ„์น˜ํ•œ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.

์Šคํƒ์„ ํ™œ์šฉํ•˜๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅํ•œ๋ฐ, ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ํฌ๊ธฐ ๋•Œ๋ฌธ์— (10^5)

๋ฌธ์ž์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ์ž๋ฃŒ๊ตฌ์กฐ์— ํ•˜๋‚˜์”ฉ push, pop ํ•˜๊ธฐ ๋ณด๋‹ค๋Š” ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

๊ทœ์น™์„ ํ™œ์šฉํ•ด์„œ ๋ฌธ์ž์—ด์˜ ๊ฐ€์žฅ ๋’ค์ชฝ ๋ถ€ํ„ฐ ์ˆœํšŒ๋ฅผ ํ•ด์ค๋‹ˆ๋‹ค.

์ด๋•Œ * ๋ฅผ ๋งŒ๋‚˜๋ฉด answer ์— ์ถ”๊ฐ€ํ•˜์ง€ ์•Š๊ณ  ๋ณ„ํ‘œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ณ„์† ์„ธ์–ด์ฃผ๋‹ค๊ฐ€ ์ผ๋ฐ˜ ์•ŒํŒŒ๋ฒณ์„ ๋ฐœ๊ฒฌํ•˜๋ฉด ์ €์žฅํ•ด๋†จ๋˜ ๋ณ„ํ‘œ ๊ฐœ์ˆ˜๋ฅผ ํ•˜๋‚˜์”ฉ ์ค„์ด๊ณ , ๋งŒ์•ฝ ์ €์žฅ๋˜์–ด์žˆ๋Š” ๋ณ„ํ‘œ ๊ฐœ์ˆ˜๊ฐ€ ์—†๋‹ค๋ฉด ๊ทธ ๋ฌธ์ž๋ฅผ answer ์— ์ถ”๊ฐ€ํ•ด์ค๋‹ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด O(n) ์˜ ์‹œ๊ฐ„๋ณต์žก๋„์— O(1) ์˜ ๊ณต๊ฐ„๋ณต์žก๋„๋กœ ํ•ด๊ฒฐ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

๐Ÿ‘จ‍๐Ÿ’ป ์ฝ”๋“œ

/**
 * @param {string} s
 * @return {string}
 */
var removeStars = function(s) {
    let answer = ''
    let asterikCount = 0

    for (let i = s.length-1; i >= 0; i -= 1) {
        if (s[i] === '*') {
            asterikCount += 1
        } else {
            if (asterikCount > 0) {
                asterikCount -= 1
            } else {
                answer = s[i]+answer
            }
        }
    }

    return answer
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 42 - Trapping Rain Water (Hard)  (0) 2023.04.30
LeetCode 238 - Product of Array Except Self (Medium)  (2) 2023.04.24
LeetCode 1603 - Design Parking System (Easy)  (0) 2023.04.24
LeetCode 15 - 3Sum (Medium)  (0) 2023.04.24
LeetCode 13 - Roman to Integer (Easy)  (0) 2023.04.24

๐Ÿ’ฌ ๋Œ“๊ธ€