Easy O(n) Java Solution


  • 0
    S
    public class Solution {
        public String licenseKeyFormatting(String S, int K) {
            StringBuilder sb = new StringBuilder();
            char[] arr = S.toCharArray();
            int cnt = 0;
            for (int i= arr.length-1; i >= 0; i--) {
                char curr = arr[i];
                if (curr == '-') continue;
                sb.insert(0, Character.toUpperCase(curr));
                cnt++;
                if (cnt == K) {
                    sb.insert(0, '-');
                    cnt = 0;
                }
            }
            if(sb.length() > 0 && sb.charAt(0) == '-') sb.deleteCharAt(0);
            return sb.toString();
        }
    }
    

Log in to reply
 

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