Skip to content

[Algorithm] NestingΒ #148

Closed
Closed
@hwangJi-dev

Description

@hwangJi-dev

πŸ’¬Β λ¬Έμ œ

https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/


πŸ’¬Β Idea

  • Sλ₯Ό λŒλ©΄μ„œ β€œ(”가 λ‚˜μ™”μ„ λ•ŒλŠ” μŠ€νƒμ— μ§‘μ–΄λ„£λŠ”λ‹€. (즉, μŠ€νƒμ—λŠ” β€œ(β€λ§Œ μ €μž₯λœλ‹€.)
  • β€œ)”가 λ‚˜μ™”μ„ λ•Œ
    • μŠ€νƒμ΄ λΉ„μ–΄μžˆλ‹€λ©΄, μ€‘μ²©λ˜μ§€ μ•Šμ€ λ¬Έμžμ—΄μ„ λœ»ν•˜λ―€λ‘œ 0을 λ¦¬ν„΄ν•˜κ³  ν•¨μˆ˜λ₯Ό μ’…λ£Œν•œλ‹€.
    • μŠ€νƒμ΄ λΉ„μ–΄μžˆμ§€ μ•Šλ‹€λ©΄ β€œ)β€μ˜ 짝인 β€œ(”가 μŠ€νƒμ— 1개 이상 λ“€μ–΄μžˆλ‹€λŠ” μ˜λ―Έμ΄λ―€λ‘œ μŠ€νƒμ˜ λ§ˆμ§€λ§‰ μ›μ†Œλ₯Ό popν•˜μ—¬ 짝을 μ œκ±°ν•΄μ€€λ‹€.
  • ν•΄λ‹Ή μž‘μ—… μˆ˜ν–‰ ν›„ μŠ€νƒμ΄ λΉ„μ–΄μžˆμ§€ μ•Šλ‹€λ©΄(== μŠ€νƒμ— β€œ(”가 λ‚¨μ•„μžˆλ‹€λ©΄) μ€‘μ²©λ˜μ§€ μ•Šμ€ λ¬Έμžμ—΄μž„μ„ λœ»ν•˜λ―€λ‘œ 0을 λ¦¬ν„΄ν•˜κ³ , μŠ€νƒμ΄ λΉ„μ–΄μžˆλ‹€λ©΄ 1을 λ¦¬ν„΄ν•˜λ©° ν•¨μˆ˜λ₯Ό μ’…λ£Œν•œλ‹€.

πŸ’¬Β ν’€μ΄

public func solution(_ S : inout String) -> Int {
    var stack: [Character] = []
    
    for i in S {
        if i == "(" {
            stack.append(i)
        } else {
            if stack.isEmpty {
                return 0
            } else {
                stack.popLast()
            }
        }
    }
    
    return stack.isEmpty ? 1 : 0
}

μ†Œμš”μ‹œκ°„ : 10λΆ„

μ‹œκ°„ λ³΅μž‘λ„ : O(N)

ν‰κ°€ν‘œ : https://app.codility.com/demo/results/trainingUU25J9-BGK/

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions