파이썬 알고리즘 문제 풀이

[HackerRank] Bigger is Greater 파이썬

gogi masidda 2024. 2. 3. 16:38

https://www.hackerrank.com/challenges/bigger-is-greater/problem?isFullScreen=true

 

Bigger is Greater | HackerRank

Rearrange the letters of a string to construct another string such that the new string is lexicographically greater than the original.

www.hackerrank.com

 

def biggerIsGreater(w): 
	#w를 list로 만들기
    w = list(w)
    #i번째가 i+1보다 작으면 반복을 멈추기
    i = len(w) - 2
    while i >= 0 and w[i] >= w[i+1]:
        i -= 1
    #i가 -1이면 찾을 수 없는 것.
    if i == -1:
        return "no answer"
    #i번째보다 뒤에서 i보다 큰 것 찾기
    j = len(w) - 1
    while w[j] <= w[i]:
        j -= 1
    #i번째와 j번째 교환
    w[i], w[j] = w[j], w[i]
    #i번째 뒤는 정렬
    w[i+1:] = sorted(w[i+1:])
    return ''.join(w)
728x90