주어진 문자보다 가장 처음으로 큰 숫자를 찾아 반환하는 코드를 짜시오
문제 풀이
주어진 문자보다 가장 처음으로 큰 숫자를 반환하여야 한다.
단, 주어진 문자가 주어진 문자리스트의 모든 문자보다 클 경우에는 list의 가장 처음 문자를 반환하면 된다.
"Letters also wrap around" 라는 문제 조건이 있기 때문이다.
파이썬 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution:
def nextGreatestLetter(self, letters, target: str) -> str:
target = ord(target)
for letter in letters:
if target < ord(letter):
return letter
return letters[0]
s = Solution()
print(s.nextGreatestLetter(["c", "f", "j"], 'a')) # c
print(s.nextGreatestLetter(["c", "f", "j"], 'c')) # f
print(s.nextGreatestLetter(["c", "f", "j"], 'd')) # f
print(s.nextGreatestLetter(["c", "f", "j"], 'g')) # j
print(s.nextGreatestLetter(["c", "f", "j"], 'j')) # c
print(s.nextGreatestLetter(["c", "f", "j"], 'k')) # c
|
cs |
'온라인 코딩 테스트 문제 풀이 > LeetCode 문제 풀이' 카테고리의 다른 글
Python으로 푸는 LeetCode 938. Range Sum of BST (Easy) (0) | 2019.06.14 |
---|---|
Python으로 푸는 LeetCode 506. Relative Ranks (Easy) (0) | 2019.05.16 |
Python으로 푸는 LeetCode 599. Minimum Index Sum of Two Lists (Easy) (0) | 2019.05.07 |
Python으로 푸는 LeetCode 917. Reverse Only Letters (Easy) (0) | 2019.05.06 |