License Key Formatting

I selected the License Key Formatting challenge at LeetCode. You can find the requirements at the following URL: https://leetcode.com/problems/license-key-formatting/

Following is a screen capture of the console of the Eclipse IDE with the first of the two test inputs:

2-4A0r7-4k

4

<<< s ==>2-4A0r7-4k<==

<<< k: 4

24A0-R74K

The console with the second test data:

2-4A0r7-4k

3

<<< s ==>2-4A0r7-4k<==

<<< k: 3

24-A0R-74K

My test code and solution in Java follows:

import java.util.Scanner;

public class Solution {

/**

*

*/

static String licenseKeyFormatting(String S, int K) {

// **** remove ‘-‘s and convert to UPPER case ****

S = S.replaceAll(“-“, “”);

S = S.toUpperCase();

// **** compute leading number of characters ****

int leading = S.length() % K;

String license = S.substring(0, leading);

// **** loop appending rest of license ****

for (int i = leading; i < S.length(); i += K) {

if (i != 0)

license += “-“;

license += S.substring(i, i + K);

}

// **** ****

return license;

}

/**

* test code

*/

public static void main(String[] args) {

// **** ****

Scanner sc = new Scanner(System.in);

// **** read string ****

String s = sc.nextLine();

System.out.println(“<<< s ==>” + s + “<==”);

// **** read K ****

int k = sc.nextInt();

System.out.println(“<<< k: ” + k);

// **** close scanner ****

sc.close();

// **** format license ****

System.out.println(licenseKeyFormatting(s, k));

}

}

I did use the following additional test strings to test my code:

gi38-d7-d-9u

4

x

1

If you have comments or questions regarding this or any other post in this blog please send me a message. I will not use your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *