Easy Java O(n) time solution with explanation


  • 0
    N
    1. Convert the string to upper case
    2. Remove all the '-' from the string
    3. Loop starting from i - k to add the hyphens ('-') at regular jumps of k.
    public class Solution {
        public String licenseKeyFormatting(String s, int k) {
            s = s.toUpperCase();
            s = String.join("", s.split("-"));
            int n = s.length();
            StringBuilder sb = new StringBuilder();
            
            for (int i = n - k; ; i -= k) {
                if (i > 0) {
                    sb.insert(0, "-" + s.substring(i, i + k));
                }
                else {
                    //substring before the first '-' from left
                    sb.insert(0, s.substring(0, i + k));
                    break;
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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