9 ms Java solution beats 99.89%


  • 0
    C

    Using StringBuffer is ok, but when i was looking at this question, i would thought what the interviewer wanted might be different than just using string buffer. Plus, working on String is not very efficient.

    Just convert string to char array, and do two passes. the first pass remove all dashes, the second pass added the dashes to the desired place.

    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            char[] a = S.toCharArray();
            int current = a.length - 1;
            while (current >= 0 && a[current] != '-') { current--; }
            
            int next = current;
            while(next >= 0 && a[next] == '-') { next--; }
            while (next >= 0) {
                a[current--] = a[next--];
                while(next >= 0 && a[next] == '-') { next--; }
            }
            
            int newLength = (a.length - current - 2) / K +  (a.length - current - 1);
            char[] b = new char[newLength];
            int ac = a.length - 1;
            int counter = 0;
            for (int i = newLength - 1; i >= 0; i--) {
                if (counter != K) {
                    if (a[ac] >= 'a' && a[ac] <= 'z') {
                        b[i] =  Character.toUpperCase(a[ac]);
                    } else {
                        b[i] = a[ac];
                    }
                    ac--;
                    counter++;
                } else {
                    b[i] = '-';
                    counter = 0;
                }
            }
            return new String(b);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.