119、密钥格式化

题目描述
给定一个密钥字符串S,只包含字母,数字以及 ‘-’(破折号)。N 个 ‘-’ 将字符串分成了 N+1 组。给定一个数字 K,重新格式化字符串,除了第一个分组以外,每个分组要包含 K 个字符,第一个分组至少要包含 1 个字符。两个分组之间用 ‘-’(破折号)隔开,并且将所有的小写字母转换为大写字母。

给定非空字符串 S 和数字 K,按照上面描述的规则进行格式化。

示例 1:

输入:S = “5F3Z-2e-9-w”, K = 4

输出:“5F3Z-2E9W”

解释:字符串 S 被分成了两个部分,每部分 4 个字符;
注意,两个额外的破折号需要删掉。
示例 2:

输入:S = “2-5g-3-J”, K = 2

输出:“2-5G-3J”

解释:字符串 S 被分成了 3 个部分,按照前面的规则描述,第一部分的字符可以少于给定的数量,其余部分皆为 2 个字符。

写了半天竟然超时了,尝试换种思路继续

 StringBuilder sb = new StringBuilder();
        for(int i = S.length() - 1; i >= 0; i--){
            if(S.charAt(i) != '-')
                sb.append(sb.length() % (K + 1) == K ? '-' : "").append(S.charAt(i));
        }
        return sb.reverse().toString().toUpperCase();

不得不说这个思路很好,比我的那个既不冗余也有效率,难受啊

排名靠前的代码

class Solution {
    public String licenseKeyFormatting(String S, int K) {
        if(S.length()<=K){
            S = S.replaceAll("-","");
            return S.toUpperCase();
        }
        char[] c = S.toCharArray();
        int len = c.length-1;
        int k = c.length+c.length/K+1;
        char[] temp = new char[k];
        k=k-1;
        int count =0;
        for(int i=len;i>=0;i--){
            if(c[i] == '-'){
               continue;
            }else{
                count++;
                if(c[i]>=97 && c[i]<=122){
                    temp[k--] = (char)(c[i]-32);
                }else{
                    temp[k--] = c[i];
                }
                if(count%K ==0){
                    if(k>=0) {
                        temp[k--] = '-';
                    }
                    count=0;
                }
            }
        }
        if(temp[k+1] == '-'){
            char[] res = new char[temp.length-k-2];
            System.arraycopy(temp,k+2,res,0,res.length);
            return new String(res);
        }else{
            char[] res = new char[temp.length-k-1];
            System.arraycopy(temp,k+1,res,0,res.length);
            return new String(res);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34446716/article/details/85195785