题目
类型:String
解题思路
- 从字符串 s 的末尾开始往前取出字符构建新的字符串 ans。每次取出字符时首先判断该字符是否为破折号,如果为破折号则跳过;否则将当前的字符计数 cnt 加 1,同时检查如果当前字符为小写字母则将其转化为大写字母,将当前字符加入到字符串 ans 的末尾。
- 对字符进行计数时,每隔 k 个字符就在字符串 ans 中添加一个破折号。特殊情况需要处理,字符串 ans 的最后一个字符为破折号则将其去掉。
- 对已经构建的字符串 ans 进行反转即为返回结果。
代码
class Solution {
public String licenseKeyFormatting(String s, int k) {
StringBuilder ans = new StringBuilder();
int cnt = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != '-') {
cnt++;
ans.append(Character.toUpperCase(s.charAt(i)));
if (cnt % k == 0) {
ans.append("-");
}
}
}
if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') {
ans.deleteCharAt(ans.length() - 1);
}
return ans.reverse().toString();
}
}