개발에 AtoZ까지

[JAVA][Array] LicenseKey Formatting 본문

코딩테스트 준비/기타문제

[JAVA][Array] LicenseKey Formatting

AtoZ 개발자 2021. 1. 27. 15:03
반응형

1. 문제

You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above.

input String str = "8F3Z-2e-9-w";
String str = "8-5g-3-J";
int k =4;
Output : 8F3Z-2E9W , 8-5G3J

2. 문제 해설

뒤에서부터 K길이만큼 자르고, 소문자는 대문자로 변환해주어 새로운 문자열을 만들어라

3. 코드 포맷

public class LicenseKeyFormatting {
	public static void main(String[] args) {

		String S = "5F3Z-2e-9-w";
		String str = "8-5g-3-J";
		int k = 2;
		System.out.println(licenseKeyFormatting(S, k));
	}
}

 

4. 접근 방법

1) 소문자를 대문자로 변환해준다.

2) -을 제거한 문자를 받아온다.

3) 뒤에서부터 K길이만큼 씩 '-'을 붙여준다.

5. 코드

import java.util.Stack;

public class LicenseKeyFormatting {
	public static void main(String[] args) {

		String S = "5F3Z-2e-9-w";
		String str = "8-5g-3-J";
		int k = 4;
		System.out.println(licenseKeyFormatting(str, k));
	}

	private static String licenseKeyFormatting(String s, int k) {
		//문자의 뒷부분부터 K만큼을 계산하기 위해 stack 사용
		Stack<Character> stack = new Stack<Character>();
		//stack의 있는 개수를 계산하기 위해서
		int index=0;
		//소문자를 대문자로 변환한고 -를 제거
		s = s.toUpperCase().replace("-","");

		for(int i=s.length()-1;i>=0;i--) {
			stack.add(s.charAt(i));
			index++;
			if(index>=k&&index%k==0&&i!=0){
				stack.add('-');
			}
		}
		//결과 담기
		String result="";
		while(!stack.isEmpty()) {
			result+=stack.pop();
		}
			
		return result;
	}
}

 

반응형

'코딩테스트 준비 > 기타문제' 카테고리의 다른 글

[JAVA][Array] Unique Email Address  (0) 2021.02.05
[JAVA][Array] PlusOne  (0) 2021.02.01
[JAVA][Array] KClosestPointstoOrigin  (0) 2021.02.01
[JAVA][Array] Jewels And Stones  (0) 2021.01.27
[JAVA][Array] MeetingRoom2  (0) 2021.01.26
[JAVA][Array] MergeInterval  (0) 2021.01.26
[JAVA][Array] Daily Temperature  (0) 2021.01.26
Comments