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๋ฅผ ํฌํ•จํ•ด์•ผํ•œ๋‹ค. ๊ฒŒ๋‹ค๊ฐ€, ๋‘ ๊ฐœ์˜ ๊ทธ๋ฃน ์‚ฌ์ด์— ๋Œ€์‰ฌ๊ฐ€ ์‚ฝ์ž…๋˜์–ด์•ผ ํ•˜๊ณ  ๋ชจ๋“  ์†Œ๋ฌธ์ž๋Š” ๋Œ€๋ฌธ์ž๋กœ ๋ณ€ํ™˜๋˜์–ด์•ผ ํ•œ๋‹ค.

  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.

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 ์–ธ์–ด๋กœ ๊ตฌํ˜„ #2.(์ •๋‹ต)

์ •๋‹ต :

Last updated

Was this helpful?