482. License Key Formatting解题报告

本文介绍了一种算法,用于格式化软件许可密钥。该算法能够根据指定长度重新组织密钥字符串,并确保所有字母转换为大写。通过实例展示了不同长度划分下的格式化效果。

482. License Key Formatting

1、原题:

Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.

We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.

So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.

Example 1:

Input: S = "2-4A0r7-4k", K = 4

Output: "24A0-R74K"

Explanation: The string S has been split into two parts, each part has 4 characters.

Example 2:

Input: S = "2-4A0r7-4k", K = 3

Output: "24-A0R-74K"

Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said above.

2、题目理解与解题思路

这道题目比较简单,大意是给你一个非空的字符串S,然后给你一个正整数K,将字符串(“-”不算)用“-”分割,除了第一段字符数可以小于K外,其它字段都要等于K。

那解题思路也就很简单了:

  1. 去除原字符串中的“-”字符。
  2. 计算字符串长度,计算其根据K可以划分为几段,其余数是多少(余数为第一段长度),若余数为0,则第一段长度为K。
  3. 根据处理过的字符串和步骤二中计算的结果构建新的字符串。

3、解题代码

public class Solution {
    public String licenseKeyFormatting(String S, int K) {
        S = S.toUpperCase();


        //将“-”用“”替换,方便计算字符串长度
		S = S.replaceAll("-","");
		if (S.length() <= 0) {
			return new String();
		}
		
		//计算余数
	    int remaider = S.length() % K;
	    //计算划分为几块
	    int groups = S.length() / K;
	    
	    
	    int setw;
	    StringBuilder s1 = new StringBuilder();
	    //若余数为0,第一块为K,否则为余数长度
	    if (remaider == 0) {
	    	s1.append(S.substring(0, K));
	    	setw = K-1;
	    } else {
	    	groups++;
	    	s1.append(S.substring(0, remaider));
	    	setw = remaider-1;
	    }
	    
	    //构建新的字符串
	    for (int i = 1; i < groups; i++) {
	    	s1.append("-");
	    	s1.append(S.substring(setw + 1, setw + K + 1));
	    	setw = setw + K;
	    }
	    
	    return s1.toString();
    }
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值