Skip to content

Commit c8d006b

Browse files
committed
solve problem License Key Formatting
1 parent ed84039 commit c8d006b

File tree

5 files changed

+75
-0
lines changed

5 files changed

+75
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ All solutions will be accepted!
172172
|160|[Intersection Of Two Linked Lists](https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/)|[java/py/js](./algorithms/IntersectionOfLinkedLists)|Easy|
173173
|860|[LemonadeChange](https://leetcode-cn.com/problems/lemonade-change/description/)|[java/py/js](./algorithms/LemonadeChange)|Easy|
174174
|401|[Binary Watch](https://leetcode-cn.com/problems/binary-watch/description/)|[java/py/js](./algorithms/BinaryWatch)|Easy|
175+
|482|[License Key Formatting](https://leetcode-cn.com/problems/license-key-formatting/description/)|[java/py/js](./algorithms/LicenseKeyFormatting)|Easy|
175176

176177
# Database
177178
|#|Title|Solution|Difficulty|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# License Key Formatting
2+
This problem is easy to solve
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public String licenseKeyFormatting(String S, int K) {
3+
S = S.toUpperCase();
4+
5+
StringBuilder res = new StringBuilder();
6+
int count = 0;
7+
8+
for (int i = S.length() - 1; i >= 0; i--) {
9+
char c = S.charAt(i);
10+
11+
if (c != '-') {
12+
if (count == K) {
13+
res.insert(0, '-');
14+
res.insert(0, c);
15+
count = 1;
16+
} else if (count < K) {
17+
res.insert(0, c);
18+
count++;
19+
}
20+
}
21+
}
22+
23+
return res.toString();
24+
}
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {string} S
3+
* @param {number} K
4+
* @return {string}
5+
*/
6+
var licenseKeyFormatting = function(S, K) {
7+
S = S.toUpperCase()
8+
9+
let res = '',
10+
count = 0
11+
12+
for (let i = S.length - 1; i >= 0; i--) {
13+
if (S[i] !== '-') {
14+
if (count === K) {
15+
res = S[i] + '-' + res
16+
count = 1
17+
} else if (count < K) {
18+
res = S[i] + res
19+
count++
20+
}
21+
}
22+
}
23+
24+
return res
25+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution(object):
2+
def licenseKeyFormatting(self, S, K):
3+
"""
4+
:type S: str
5+
:type K: int
6+
:rtype: str
7+
"""
8+
S = S.upper()
9+
res = ''
10+
11+
count = -1
12+
13+
length = len(S)
14+
for i in range(length):
15+
if S[length - 1 - i] != '-':
16+
if count == K - 1:
17+
res = S[length - 1 - i] + '-' + res
18+
count = 0
19+
elif count < K - 1:
20+
res = S[length - 1 - i] + res
21+
count += 1
22+
return res

0 commit comments

Comments
 (0)