티스토리 뷰

728x90

 

 

주어진 문자열 S를 첫번째 파트 외에는 모두 K개씩 끊어 포매팅 된 대문자 형태로 변환하는 문제이다.

e.g. 2-5g3-J, 2 →2-5G-3J

 

String과 int를 매개변수로 받는 solve 메서드의 틀이 주어진다.

 

Problem : 

public class LicenseKeyFormatting {
    public String licenseKeyFormatting(String S, int K) {

    }
}

풀이는 주어진 solvelicenseKeyFormatting 메서드에 작성하면 된다.

 

Solution :

  1. 주어진 문자열에서 "-"를 제거하고 대문자로 변환한다.
  2. 변환된 문자열에 뒤에서부터 K번째 마다 "-"를 삽입한다. (첫번째 파트 외에는 K개 단위로 나누기 위함)
public class LicenseKeyFormatting {

    // time complexity : for loop -> O(n)
    // space complexity : StringBuilder -> O(n)
    public String licenseKeyFormatting(String S, int K) {

        // S -> remove "-", toUpperCase
        StringBuilder sb = new StringBuilder(S.replaceAll("-", "").toUpperCase());

        // insert "-" from behind
        for(int i = sb.length()-K; i > 0; i=i-K){
            sb.insert(i, "-");
        }

        return sb.toString();
    }
}

 

Complexity :

  • 시간복잡도 (Time Complexity)
    • 주어진 문자열 길이에 따라 for문 반복에 따라 O(n)
  • 공간복잡도 (Space Complexity)
    • 주어진 문자열 길이에 따라 StringBuilder에 담으므로 O(n)

 

Sample(Test) :

public class LicenseKeyFormatting {

    // time complexity : for loop -> O(n)
    // space complexity : StringBuilder -> O(n)
    public String licenseKeyFormatting(String S, int K) {

        // S -> remove "-", toUpperCase
        StringBuilder sb = new StringBuilder(S.replaceAll("-", "").toUpperCase());

        // insert "-" from behind
        for(int i = sb.length()-K; i > 0; i=i-K){
            sb.insert(i, "-");
        }

        return sb.toString();
    }

    public static void main(String[] args){
     String S = "2-5g3-J";
     int K =  2;

     LicenseKeyFormatting l = new LicenseKeyFormatting();
     System.out.println(l.licenseKeyFormatting(S, K));
    }
}

 

위 테스트 코드를 실행한 결과는 다음과 같다.

2-5G-3J

 

728x90
Total
Today
Yesterday
«   2024/05   »
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 31
05-05 19:35