Short and fast Java solution


  • 0
    I
        public String licenseKeyFormatting(String S, int K) {
            StringBuilder sb = new StringBuilder();
            int count = 0;
            
            for (int i=S.length()-1;i>=0;i--) {
                if (S.charAt(i)!='-') {
                    sb.append(Character.toUpperCase(S.charAt(i)));
                    if (++count % K == 0) sb.append("-");
                }
            }
    
            if (sb.length() > 0 && sb.charAt(sb.length()-1)=='-') sb.setLength(sb.length()-1);
    
            return sb.reverse().toString();
        }
    

  • 0
    X

    Is there a way to avoid using the build-in function str.toLowerCase() or str.toUpperCase()?
    I was trying to do sth like +/- 32 to convert upper to lower. But it failed. Anyone knows why?


  • 1
    I

    @xin77 Solution without toUpperCase:

        public String licenseKeyFormatting(String S, int K) {
            StringBuilder sb = new StringBuilder();
            int count = 0;
    
            for (int i=S.length()-1;i>=0;i--) {
                char ch = S.charAt(i);
                if (ch!='-') {
                    if (ch>='a' && ch <='z') ch = (char)(ch + ('A'-'a'));
                    sb.append(ch);
                    if (++count % K == 0) sb.append("-");
                }
            }
    
            if (sb.length() > 0 && sb.charAt(sb.length()-1)=='-') sb.setLength(sb.length()-1);
    
            return sb.reverse().toString();
        }
    

  • 0
    X

    @ignath thank u!


Log in to reply
 

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