Java solution without fancy system methods (such as reverse(), toUppercase())


  • 0
    Y
    public class Solution {
        
        public int index = 0;
        
        public String licenseKeyFormatting(String S, int K) {
            int n = S.length();
            int count = 0;
            
            for (int i = 0; i < n; i++)
                if (S.charAt(i) == '-')
                    count++;
                    
            n -= count;
            
            StringBuilder sb = new StringBuilder();
            
            for (int i = 0; i < n % K; i++)
                sb.append(helper(S));
                
            if ((n % K != 0) && (n / K != 0))
                sb.append("-");
            
            for (int i = 0; i < n / K; i++) {
                for (int j = 0; j < K; j++)
                    sb.append(helper(S));
                    
                if (i != n / K - 1)
                    sb.append("-");
            }
            
            return sb.toString();
        }
        
        public char helper(String S) {
            while (S.charAt(index) == '-') index++;
            
            char c = S.charAt(index);
            if (c <= 'z' && c >= 'a') {
                c += ('A' - 'a');
            }
            index++;
            return c;
        }
    }
    

Log in to reply
 

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