482. License Key Formatting

 avatar
unknown
java
3 years ago
766 B
5
Indexable
class Solution {
    public String licenseKeyFormatting(String s, int k) {
        String stringWithNoDashes = s.replace("-", "");
        StringBuilder newString = new StringBuilder();

        int j = 0;
        // loop through the string with no dashes in reverse
        // add a dash after every k characters
        for (int i = stringWithNoDashes.length() - 1; i >= 0; i--) {
            // if the index j is at 0, we should not add a dash
            if (j % k == 0 && j != 0) {
                newString.append('-');
            }
            newString.append(stringWithNoDashes.charAt(i));
            j++;
        }

        // reverse it back to it's original and make it all uppercase
        return newString.reverse().toString().toUpperCase();
    }
}
Editor is loading...