2021.10.04 - 111.密钥格式化

1. 题目

在这里插入图片描述

2. 思路

(1) char[]

  • 从后往前遍历字符串,利用char[]存储字符串中的非’-‘字符,每隔k个字符添加一个’-'字符即可。
  • char[]的初始化长度为字符串长度的两倍,因为可能字符串中都是非’-'字符,且k的值为1。

(2) StringBuilder

  • 从前往后遍历字符串,利用StringBuilder进行存储,最后将StringBuilder反转即可。

  • (1)只需遍历一遍,(2)需要遍历两遍。

3. 代码

import java.util.Arrays;

public class Test {
    
    
    public static void main(String[] args) {
    
    
        Solution solution = new Solution();
        System.out.println(solution.licenseKeyFormatting("aaaa", 2));
    }
}

class Solution {
    
    
    public String licenseKeyFormatting(String s, int k) {
    
    
        char[] res = new char[s.length() * 2];
        int strIndex = s.length() - 1;
        int resIndex = res.length - 1;
        int count = 0;
        while (strIndex >= 0) {
    
    
            while (strIndex >= 0 && count < k) {
    
    
                if (s.charAt(strIndex) != '-') {
    
    
                    res[resIndex--] = Character.toUpperCase(s.charAt(strIndex));
                    count++;
                }
                strIndex--;
            }
            if (strIndex >= 0 && count == k) {
    
    
                res[resIndex--] = '-';
            }
            count = 0;
        }
        if (resIndex + 1 < res.length && res[resIndex + 1] == '-') {
    
    
            return String.valueOf(Arrays.copyOfRange(res, resIndex + 2, res.length));
        }
        return String.valueOf(Arrays.copyOfRange(res, resIndex + 1, res.length));
    }
}

class Solution1 {
    
    
    public String licenseKeyFormatting(String s, int k) {
    
    
        StringBuilder res = new StringBuilder();
        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
    
    
            if (s.charAt(i) != '-') {
    
    
                res.append(Character.toUpperCase(s.charAt(i)));
                count++;
                if (count % k == 0) {
    
    
                    res.append("-");
                }
            }
        }
        if (res.length() > 0 && res.charAt(res.length() - 1) == '-') {
    
    
            res.deleteCharAt(res.length() - 1);
        }
        return res.reverse().toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120617005