class Solution {
public String licenseKeyFormatting(String s, int k) {
/** 遍历 s, 确定格式化后的密钥长度 */
int numLetterOrDigits = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.isLetterOrDigit(s.charAt(i))) numLetterOrDigits++;
}
int sz = numLetterOrDigits;
if (sz == 0) return "";
sz += numLetterOrDigits % k == 0 ? numLetterOrDigits / k - 1 : numLetterOrDigits / k;
char[] ans = new char[sz];
/** 双指针 */
int ptrS = s.length() - 1, ptrANS = ans.length - 1, cnt = 0;
while (ptrS >= 0) {
if (cnt == k && ptrANS > -1) { ans[ptrANS--] = '-'; cnt = 0; }
else {
char ch = s.charAt(ptrS--);
if (Character.isDigit(ch)) {
cnt++;
ans[ptrANS--] = ch;
}
else if (Character.isLetter(ch)) {
cnt++;
ans[ptrANS--] = Character.toUpperCase(ch);
}
}
}
return String.valueOf(ans);
}
}