Easy to understand using StringBuilder


  • 7
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            // Replacing all - and converting all letters to uppercase
            String S1 = S.replace("-","");
            S1 = S1.toUpperCase();
            
            // Making stringBuilder 
            StringBuilder sb = new StringBuilder();
             for(int i=0; i<S1.length();i++) {
                sb.append(S1.charAt(i));
            }
            int len = sb.toString().length();
            // Inserting '-' from back at every K position
            for(int i=K; i < len; i=i+K) {
                    sb.insert(len-i,'-');
                }
            return sb.toString();   
        }
    }
    
    

  • 1
    P

    Might wanna remove that stray

    System.out.println(i);

  • 0

    @pras00n Done. Thanks for pointing it out.


  • 0
    Z

    @hemantpandey Good idea to insert '-' from back!


  • 2
    Z

    @hemantpandey Maybe there is no need to go through S to build the StringBuilder? That will be more concise then.

    public String licenseKeyFormatting(String S, int K) {
        S = S.replace("-","").toUpperCase();
        // Making stringBuilder 
        StringBuilder sb = new StringBuilder();
        sb.append(S);
                
        int len = S.length();
        // Inserting '-' from back at every K position
        for(int i=K; i < len; i=i+K) {
                sb.insert(len-i,'-');
        }
        return sb.toString();   
    }
    
    

  • 0
    A

    How come string.replace() runs faster than looping over and checking for "-" directly? This runs faster than the native loop, non-striped solution. Isn't string.replace() using regex under the hood, hence should be slower?


Log in to reply
 

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