Advertisement
lifeiteng

482. License Key Formatting

Sep 10th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. class Solution {
  2.     public String licenseKeyFormatting(String S, int K) {
  3.         StringBuilder sb = new StringBuilder(), sb2 = new StringBuilder();
  4.         for(char ch : S.toCharArray())
  5.         {
  6.             if(ch == '-') continue;
  7.             if(Character.isLowerCase(ch)) ch = Character.toUpperCase(ch);
  8.             sb.append(ch);
  9.         }
  10.         int n = sb.length();
  11.         for(int i = n - 1, count = 0; i >= 0; i--)
  12.         {
  13.             sb2.append(sb.charAt(i));
  14.             count++;
  15.             if(count % K == 0)
  16.             {
  17.                 sb2.append('-');
  18.                 count = 0;
  19.             }
  20.         }
  21.         n = sb2.length();
  22.         if(n > 1 && sb2.charAt(n - 1) == '-') sb2.deleteCharAt(n - 1);
  23.         return sb2.reverse().toString();
  24.        
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement