๐ŸŒฑ → ๐ŸŒณ

[๋ฐฑ์ค€] 9093๋ฒˆ: ๋‹จ์–ด ๋’ค์ง‘๊ธฐ python ๋ณธ๋ฌธ

Algorithms

[๋ฐฑ์ค€] 9093๋ฒˆ: ๋‹จ์–ด ๋’ค์ง‘๊ธฐ python

BAY 2023. 1. 2. 11:14
728x90

https://www.acmicpc.net/problem/9093

 

9093๋ฒˆ: ๋‹จ์–ด ๋’ค์ง‘๊ธฐ

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๋ฌธ์žฅ์ด ํ•˜๋‚˜ ์ฃผ์–ด์ง„๋‹ค. ๋‹จ์–ด์˜ ๊ธธ์ด๋Š” ์ตœ๋Œ€ 20, ๋ฌธ์žฅ์˜ ๊ธธ์ด๋Š” ์ตœ๋Œ€ 1000์ด๋‹ค. ๋‹จ์–ด์™€ ๋‹จ์–ด ์‚ฌ์ด์—๋Š”

www.acmicpc.net

 

 

stack ์ž๋ฃŒ ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„:

N=int(input())

for i in range(N):
    string=input()
    string+=" "
    stack=[]
    for j in string:
        if j!=" ":
            stack.append(j)
        else:
            while stack:
                print(stack.pop(), end='')
            print(' ', end='')

- j ๊ฐ’์ด ๊ณต๋ฐฑ์ด ์•„๋‹ ๋•Œ๋Š” stack์— i ๊ฐ’์„ ๋„ฃ๊ณ  ๊ณต๋ฐฑ์ด๋ฉด stack ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฆฌ์ŠคํŠธ์˜ ๋‚ด์šฉ์„ ์ถœ๋ ฅ์‹œํ‚ค๋„๋ก ๊ตฌํ˜„

- string += " " ์ฝ”๋“œ๋กœ ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์˜ ๋งˆ์ง€๋ง‰์— ๊ณต๋ฐฑ์„ ์ถ”๊ฐ€ํ•˜์—ฌ, ๋งˆ์ง€๋ง‰์— ๋“ค์–ด๊ฐ€๋Š” ๋‹จ์–ด๋„ stack ๋ฆฌ์ŠคํŠธ์—์„œ ๊บผ๋‚ผ ์ˆ˜ ์žˆ๋„๋ก ๊ตฌํ˜„

- end=""๋กœ ์„ ์–ธํ•˜์—ฌ ๊ฐ™์€ ๋‹จ์–ด๊ฐ€ ํ•œ ๊ธ€์ž์”ฉ ๋„์–ด์„œ ์ถœ๋ ฅ๋˜๊ฑฐ๋‚˜ ์ค„ ๋ฐ”๊ฟˆ ๋˜์–ด ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ ๋ฐฉ์ง€

 

 

Q) ๋˜‘๊ฐ™์€ ์ฝ”๋“œ์ธ๋ฐ ์™œ ์•„๋ž˜์˜ ์ฝ”๋“œ๋Š” ์ถœ๋ ฅํ˜•์‹์ด ์ž˜ ๋ชป ๋˜์—ˆ๋‹ค๊ณ  ๋œฐ๊นŒ ? ใ…œ

import sys
input = sys.stdin.readline

num = int(input())

# stack ์ž๋ฃŒ ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ 
for _ in range(num):
  cmd = input()
  cmd += " "
  stack = []
  for i in cmd:
    if i!=" ":
      stack.append(i)
    else:
      while stack:
        print(stack.pop(), end='')
      print(' ', end='')

 

 

list ๋‚ด๋ถ€์—์„œ ์ œ๊ณตํ•˜๋Š” ๊ธฐ๋Šฅ์„ ํ†ตํ•ด ๊ตฌํ˜„:

import sys
input = sys.stdin.readline

num = int(input())
for _ in range(num):
  cmd = input().split()
  for i in cmd:
    print(i[::-1], end=' ')

- input().split() ํ†ตํ•ด ์ž…๋ ฅ๋ฐ›์€ ๋ฌธ์ž์—ด ๋„์–ด์“ฐ๊ธฐ ๊ตฌ๋ถ„์œผ๋กœ list์— ์ €์žฅ 

- list ๊ฐ ์š”์†Œ์— ์ ‘๊ทผํ•˜์—ฌ [::-1]๋ฅผ ํ†ตํ•ด ๋’ค์ง‘์–ด์คŒ 

- end=' '๋กœ ๋ฌธ์ž์—ด ๋๋‚  ๋•Œ ๋„์–ด์“ฐ๊ธฐ

 

์œ„์˜ ๋ฐฉ๋ฒ• ์™ธ์—๋„ for๋ฌธ ์‚ฌ์šฉ, python ๋‚ด์žฅํ•จ์ˆ˜์ธ reverse() ์‚ฌ์šฉ ๋“ฑ์˜ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•œ๋‹ค.

728x90