---
# System prepended metadata

title: \#482 License Key Formatting
tags: [leetcode, leetcode-easy, string]

---

# \#482 License Key Formatting
## *給定一字串s和數字k, 將s以每k的長度以"-"分隔, 最後若有不足k長度的部分會位在字串開頭*
## Log
 - build 20210912 by syhuang

## 改良
 - 直接以s.charAt()跑迴圈的方式來判斷產生result
 - leetcode submit runtime 63%, memory 64%
```javascript=
var licenseKeyFormatting = function(s, k) {
    let sCount = 0;
    let result = '';
    for(let i=s.length-1; i>=0; i--){
        const c = s.charAt(i);
        if(c !== '-'){
            if(sCount==k){
                result = '-' + result;
                sCount = 0;
            }
            result = c.toUpperCase() + result;
            sCount++;
        }
    }
    return result;
};
```
## 初見
 - 將s內的"-"全數去除, 並轉大寫
 - 從字串尾端開始跑迴圈, 每k長度就insert一個"-"字元
 - leetcode submit runtime 13%, memory 38%
```javascript=
var licenseKeyFormatting = function(s, k) {
    if(k>s.replaceAll('-','').length) return s.replaceAll('-','');
    let sAry = s.replaceAll('-','').toUpperCase().split('');
    let i = sAry.length;
    for(; i>k; i-=k){
        sAry.splice(i-k,0,'-');
    }
    return sAry.join('');
};
```
## 備註
## 參考
###### tags: `leetcode`, `leetcode-easy`, `string`