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번이다.
'프로그래밍 > leetcode' 카테고리의 다른 글
[leetcode] Search a 2D matrix (0) | 2022.03.31 |
---|---|
[leetcode] 81. Search in Rotated Sorted Array II (0) | 2022.03.28 |
[leetcode] Two City Scheduling (0) | 2022.03.25 |
[leetcode] 1007. Minimum Domino Rotations For Equal Row (0) | 2022.03.21 |
[leetcode] Maximum Frequency Stack (0) | 2022.03.19 |