https://www.hackerrank.com/challenges/encryption/problem?isFullScreen=true
Encryption | HackerRank
Encrypt a string by arranging the characters of a string into a matrix and printing the resulting matrix column wise.
www.hackerrank.com
나의 코드
#!/bin/python3
import math
import os
import random
import re
import sys
def _up_r_c(r,c,L):
while True:
if r < c:
r += 1
else:
c += 1
if r*c >= L:
break
return [r,c]
def _down_r_c(r,c,L):
while True:
if min(r,c) * (max(r,c)-1) < L:
break
if r < c:
c -= 1
else:
r -= 1
return [r,c]
def encryption(s):
answer = ''
s = s.replace(' ','')
r,c,L = int(len(s)**(1/2)), int(len(s)**(1/2))+1, len(s)
rt_dict = {i:'' for i in range(c)}
if r*c < L:
r,c = _up_r_c(r,c,L)
elif r*c > L:
r,c = _down_r_c(r,c,L)
for i in range(len(s)):
rt_dict[i%c] += s[i]
answer = ' '.join(list(rt_dict.values()))
print(answer)
return answer
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = encryption(s)
fptr.write(result + '\n')
fptr.close()
시간 복잡도
s = s.replace(' ','') : 공백 제거 ( 선형 시간 복잡도 )
rt_dict = {i:'' for i in range(c)} : c길이 만큼 딕셔너리 생성 ( 선형 시간 복잡도 )
_down_r_c, _up_r_c 함수 : 조건 만족시 까지 while 문 반복 ( 선형 시간 복잡도 )
for i in range(len(s)) : 문자열을 순회하면 rt_dict 제작 ( 선형 시간 복잡도 )
' '.join() : 최종 문자열 결함 ( 선형 시간 복잡도 )
해당 알고리즘 시간복잡도는 선형 시간 복잡도 ( O(n) )
'코딩테스트 파이썬 > hackerrank' 카테고리의 다른 글
| The Time in Words (0) | 2024.10.15 |
|---|---|
| Happy Ladybugs (0) | 2024.10.14 |
| Manasa and Stones (0) | 2024.10.10 |
| Cavity Map (0) | 2024.10.08 |
| Fair Rations (0) | 2024.10.07 |