만족은 하되 안주하지는 말자

기록해야 기억한다

프로그래밍/leetcode

[leetcode] Smallest String With A Given Numeric Value

D36choi 2022. 3. 22. 23:40
728x90

문제

https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/

 

Smallest String With A Given Numeric Value - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

내 풀이

class Solution {
  public String getSmallestString(int n, int k) {
    int remain = k - n;
    char[] array = new char[n];
    Arrays.fill(array, 'a');
    
    int z = remain / 25;
    int rest = remain % 25;


    for(int i=0; i<z; i++) {
      array[i] += 25;
    }
    if(rest != 0) {
     array[z] += rest;   
    }

    StringBuilder sb = new StringBuilder();
    for(int i=n-1; i>=0; --i) {
      sb.append(array[i]);
    }

    return sb.toString();
  }
}

알게 된 것

Greedy 하게 풀어야하는 문제다. 26개 값중 가장 큰 문자인 'z'부터 n에 빼서 26보다 큰지작은지를 비교하다보면

역 사전순으로 정렬된 문자열이 나오게 된다. 이를 뒤집으면 끝

 

피드백

문자열 뒤집기는 역순 append 말고도 sb의 reverse() 를 호출하면 가능하다.

StringBuilder sb=new StringBuilder(str);  
sb.reverse();

lowercase a 는 ascii code 97번이다.