# License Key Formatting

You are given a license key represented as a string S which 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.

\=>오직 알파벳 철자와 대쉬로 이루어진 String S로 나타내지는 라이센스 키가 주어진다. String은 N개의 대쉬에 의해 N+1 그룹으로 분리된다.

숫자 K가 주어지는데, 우리는 string을 재형성하고자 한다. 각각의 그룹은 정확히 K개의 character를 포함하고, K보다 작을 수도 있는 첫번째 그룹을 제외하고 최소한 1개의 character를 포함해야한다. 게다가, 두 개의 그룹 사이에 대쉬가 삽입되어야 하고 모든 소문자는 대문자로 변환되어야 한다.

{% hint style="info" %}

1. The length of string S will not exceed 12,000, and K is a positive integer.
2. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
3. String S is non-empty.
   {% endhint %}

> Example 1 :\
> Input : S = "5F3Z-2e-9-2", K = 4\
> Output : "5F3Z-2E92"
>
> Example 2 :\
> Input : S = "2-5g-3-J",K = 2\
> Output : "2-5G-3J"

**사용할 자료구조 : StringBuilder**\
\=>**String : String의 +연산이나 concat을 사용하면 새로운 String 객체를 new로 만들기 때문에 그만큼 메모리를 많이 차지하기 때문이다.**\
\=>StringBuffer : 멀티스레드 환경에서 동기화(Synchronized)\
\=>**StringBuilder** : 싱글스레드 환경에서 비동기화(Asynchronized). **Append 등 연산을 자유자재로 쓰기 위해** 사용한다.

**알고리즘**\
1\. 원래 String에서 대쉬(-)제거한다. - **replace(char oldChar, char newChar)**\
2\. 소문자는 대문자로 바꾼다. - **toUpperCase**\
3\. **뒤에서부터 카운팅한다! - for(int i=k; i < leng; i = i+k)**

**=>더 직관적으로**

1. 새로운 String 객체를 생성하여 input String에서 대쉬 제거, 대문자 변환한다.
2. StringBuilder 생성하여 1에서 생성한 String 데이터 추가한다.
3. StringBuilder의 뒤에서부터 K만큼 끊어 대쉬 추가한다. //insert(int,'-');
4. StringBuilder를 String으로 변환하여 리턴한다.

알고리즘을 java 언어로 구현 #1.(틀림)

```java
class LicenseKeyFormatting {
    public static void main(String[] args) {
        String S = "5F3z-2e-9-w";
        int K = 4;
        
        System.out.println(solve(S,K));
    }
    public static StringBuilder solve(String s, int K) {
        StringBuilder sb = new StringBuilder();
        //String을 StringBuilder로 변환하여 복사.
        int leng = s.length();//문자열은 .length(), 배열은 .length
        for(int i = 0; i<leng;i++) {
            sb.append(s.charAt[i]);
        }
        //1.대쉬 제거
        for(int i=0;i<sb.size();i++) {
            sb.replace('-','');
        }
        //2.소문자는 대문자로 바꾼다.
        sb = sb.toUpperCase();
        //3.뒤에서부터 카운팅하고, 대쉬 추가한다!
        for(int i=k; i<leng;i=i+k) {
            sb.insert(K-i,"-");
        }
        return sb;
    }
}
```

알고리즘을 java 언어로 구현 #2.(정답)

```java
class LicenseKeyFormatting {
    public static void main(String[] args) {
        String S = "5F3z-2e-9-w";
        int K = 4;
        
        System.out.println(solve(S,K));
    }
    public static String solve(String s, int K) {
        //1.새로운 String 객체를 생성하여 input String에서 대쉬 제거, 대문자 변환한다.
        String S2 = s.replace("-","");//String은 character로 이루어져있기 때문에 각각의 char는 ' '라 생각햇지만 오답. 그래서 ""
        S2 = S2.toUpperCase();
        //2.StringBuilder 생성하여 1에서 생성한 String 데이터 추가한다.
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<S2.length();i++) {
            sb.append(S2.charAt(i));
        }
        //3.StringBuilder의 뒤에서부터 K만큼 끊어 대쉬 추가한다. insert(int,'-');
        int leng = sb.toString().length();
        for(int i=k; i<leng;i=i+k) {
            sb.insert(leng-i,'-');
        }
        //4.StringBuilder를 String으로 변환하여 리턴한다.
        return sb.toString();
    }
}
```

정답 :

```java
class LicenseKeyFormatting {
    public static void main(String[] args) {
        String S = "5F3z-2e-9-w";
        int K = 4;
        
        System.out.println(solve(S,K));
    }
    public static String solve(String s, int K) {
        //1.input String의 대쉬 제거 - StringBuilder가 아니라 input String에서 대쉬제거, 대문자 변환한다!
        String s2 = s.replace("-","");
        //2.input String 소문자는 대문자로 바꾼다.
        S2 = S2.toUpperCase();
        //3.뒤에서부터 카운팅하고, 대쉬 추가한다!
        //StringBuilder 생성, 데이터 복사
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i<s.length();i++) {//문자열은 .length(), 배열은 .length
            sb.append(s.charAt[i]);
        }
        int len = sb.toString().length();
        for(int i=k; i<len;i=i+k) {
            sb.insert(len-i,'-');
        }
        return sb.toString();
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/algorithms-problem-solving-skills/algorithm-problems/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
