题目

类型:String
image.png

解题思路

  • 从字符串 s 的末尾开始往前取出字符构建新的字符串 ans。每次取出字符时首先判断该字符是否为破折号,如果为破折号则跳过;否则将当前的字符计数 cnt 加 1,同时检查如果当前字符为小写字母则将其转化为大写字母,将当前字符加入到字符串 ans 的末尾。
  • 对字符进行计数时,每隔 k 个字符就在字符串 ans 中添加一个破折号。特殊情况需要处理,字符串 ans 的最后一个字符为破折号则将其去掉。
  • 对已经构建的字符串 ans 进行反转即为返回结果。

代码

  1. class Solution {
  2. public String licenseKeyFormatting(String s, int k) {
  3. StringBuilder ans = new StringBuilder();
  4. int cnt = 0;
  5. for (int i = s.length() - 1; i >= 0; i--) {
  6. if (s.charAt(i) != '-') {
  7. cnt++;
  8. ans.append(Character.toUpperCase(s.charAt(i)));
  9. if (cnt % k == 0) {
  10. ans.append("-");
  11. }
  12. }
  13. }
  14. if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') {
  15. ans.deleteCharAt(ans.length() - 1);
  16. }
  17. return ans.reverse().toString();
  18. }
  19. }