programming/알고리즘 풀이

[leetcode] 482. License Key Formatting

몽구스_ 2021. 6. 22. 00:05
728x90
반응형

 

 

License Key Formatting - 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

 

 

처음에 문제를 잘못 이해했다.

input : "2-4A0r7-4k" , 4 일 경우

"24A0-R74K"이 나와야 하는데, 나는 첫번째 그룹을 제외하고 그 이후를 k로 묶으라는 말로 들었다.

그래서 "2-4A0R-74K"가 나와버렸다.

 

class Solution {
    public String licenseKeyFormatting(String s, int k) {
        StringBuilder sb = new StringBuilder();
		
		int idx = s.indexOf("-");
		
		s = s.replace("-", "");
		sb.append(s);
		int end = s.length();
		
		for(int i = end - k; i > 0; i-=k) {
			sb.insert(i, "-");
		}
		
		return sb.toString().toUpperCase();
    }
}

 

처음엔 모든 -를 없애주었다.

그리고 코드를 뒤에서부터 k개씩 줄여나가서 k의 배수 되는 위치에 -를 끼워넣었다.

이 sb를 모두 대문자로 변환해 리턴해주었다.

 

 

728x90
반응형