Linear time Java solution


  • 0
    N
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            S = S.toUpperCase();
            String s = String.join("", S.split("-"));
            int n = s.length();
            StringBuilder res = new StringBuilder();
            
            for (int i = n - K; ; i -= K) {
                if (i > 0) {
                    res.insert(0, "-" + s.substring(i, i + K));
                }
                else {
                    res.insert(0, s.substring(0, i + K));
                    break;
                }
            }
            return res.toString();
        }
    }
    

Log in to reply
 

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