File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments