Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 가벼운학습지
- java
- 마이라이트
- 코테준비
- 일본어독학
- 삼성
- 스텍
- 일본어공부
- stack
- 알고리즘
- 백준
- 자바
- 일본어학습지
- SWEA
- 자바스크립트
- 코딩테스트
- 카카오
- 코테
- 프로그래머스
- array
- mybatis
- 인프런
- 코딩
- 가벼운학습지후기
- js
- javascript
- 성인학습지
- 자료구조
- 정렬
- 삼성소프트웨어아카데미
Archives
- Today
- Total
개발에 AtoZ까지
[JAVA][Array] LicenseKey Formatting 본문
반응형
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