[Programmers] 큰 수 만들기 - 탐욕법(Greedy)

동민·2021년 3월 11일
// 큰 수 만들기 - 탐욕법(Greedy)
class MakeLargeNum {
	public String solution(String number, int k) {

		StringBuilder sb = new StringBuilder(number); // 이와 같은 문제는 List보다 StringBuilder를 활용하는 것이 빠르다 (큰 데이터를 다룰 때 좋음)

		int index = 1;
		while (k > 0) {

			if (sb.charAt(index - 1) < sb.charAt(index)) {
				sb.deleteCharAt(index - 1); // index - 1 번째 문자를 삭제
				k--;
				index = 1;
				continue;
			}
			index++;
			if (index >= sb.length()) { // 654321, 1111 과 같이 숫자가 앞에서 k번 만큼 삭제 되지 않는 경우 맨 뒤에 있는 숫자를 제거 
				sb.delete(sb.length() - k, sb.length()); // StringBuilder.delete(start_index, end_index) : start_index 부터 end_index까지 문자 제거
				break;
			}

		}
		return sb.toString(); // StringBuilder 타입 -> String

	}

	public static void main(String[] args) {
		MakeLargeNum s = new MakeLargeNum();
		System.out.println(s.solution("1924", 2)); // 94
		System.out.println(s.solution("1231234", 3)); // 3234
		System.out.println(s.solution("4177252841", 4)); // 775841
		System.out.println(s.solution("654321", 2)); // 6543
		System.out.println(s.solution("1111", 2));

	}

}
List보다 StringBuilder를 활용하는 것이 빠르다 (큰 데이터를 다룰 때 좋음)

StringBuilder sb = new StringBuilder(String str);
sb.deleteCharAt(int index); // index 번째 문자를 삭제
sb.delete(int start_index, int end_index) : start_index 부터 end_index까지 문자 제거
profile
BE Developer

0개의 댓글