Skip to content

Commit 98319c0

Browse files
authored
Merge pull request soapyigu#278 from iHackSubhodip/master
[String] Solution for License Key Formatting.
2 parents c9ad8c7 + fb1bbd5 commit 98319c0

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

String/LicenseKeyFormatting.swift

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/license-key-formatting/
3+
* Primary idea: traverse the array formatted string from end. Insert the dash into the String as per given K, else insert the elements at index 0.
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(1)
6+
*
7+
*/
8+
9+
class LicenseKeyFormatting {
10+
func licenseKeyFormatting(_ S: String, _ K: Int) -> String {
11+
guard S.count > 0 && K > 0 else{
12+
return ""
13+
}
14+
15+
let upperCaseString = Array(S.uppercased())
16+
var result = [Character](), n = K
17+
18+
for i in stride(from: S.count - 1, through: 0, by: -1){
19+
let aCharacter = upperCaseString[i]
20+
guard aCharacter != "-" else{
21+
continue
22+
}
23+
24+
if n == 0{
25+
result.insert("-", at: 0)
26+
n = K
27+
}
28+
29+
result.insert(aCharacter, at: 0)
30+
n -= 1
31+
}
32+
33+
return String(result)
34+
}
35+
}

0 commit comments

Comments
 (0)