Fast different Java solution sufficiently using String

  • 0

    I think scanning the original string character by character might not be a very efficient way to solve this problem. On the contrary, removing all the dash and then inserting the new dash at appropriate position might be faster.

    public String licenseKeyFormatting(String S, int K) {
            String[] groups = S.split("-");
            StringBuilder sb = new StringBuilder();
            int numdash = 0;
            for(int i=0; i<groups.length; i++){
            if(sb.length() == 0) return "";
            int index = sb.length() % K;
            while(index < sb.length()){
                sb.insert(index, '-');
                index = index + 1 + K;
            return sb.charAt(0) == '-' ? sb.substring(1).toUpperCase() : sb.toString().toUpperCase();

Log in to reply

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