diff --git a/solution/0400-0499/0481.Magical String/README.md b/solution/0400-0499/0481.Magical String/README.md index 0866a781a5fed..312a352088e56 100644 --- a/solution/0400-0499/0481.Magical String/README.md +++ b/solution/0400-0499/0481.Magical String/README.md @@ -115,7 +115,7 @@ class Solution: ```java class Solution { public int magicalString(int n) { - List s = new ArrayList<>(Arrays.asList(1, 2, 2)); + List s = new ArrayList<>(List.of(1, 2, 2)); for (int i = 2; s.size() < n; ++i) { int pre = s.get(s.size() - 1); int cur = 3 - pre; @@ -178,17 +178,15 @@ func magicalString(n int) (ans int) { ```ts function magicalString(n: number): number { - const cs = [...'1221121']; - let i = 5; - while (cs.length < n) { - const c = cs[cs.length - 1]; - cs.push(c === '1' ? '2' : '1'); - if (cs[i] !== '1') { - cs.push(c === '1' ? '2' : '1'); + const s: number[] = [1, 2, 2]; + for (let i = 2; s.length < n; ++i) { + let pre = s[s.length - 1]; + let cur = 3 - pre; + for (let j = 0; j < s[i]; ++j) { + s.push(cur); } - i++; } - return cs.slice(0, n).reduce((r, c) => r + (c === '1' ? 1 : 0), 0); + return s.slice(0, n).filter(x => x === 1).length; } ``` @@ -197,18 +195,19 @@ function magicalString(n: number): number { ```rust impl Solution { pub fn magical_string(n: i32) -> i32 { - let n = n as usize; - let mut s = String::from("1221121"); - let mut i = 5; - while s.len() < n { - let c = s.as_bytes()[s.len() - 1]; - s.push(if c == b'1' { '2' } else { '1' }); - if s.as_bytes()[i] != b'1' { - s.push(if c == b'1' { '2' } else { '1' }); + let mut s = vec![1, 2, 2]; + let mut i = 2; + + while s.len() < n as usize { + let pre = s[s.len() - 1]; + let cur = 3 - pre; + for _ in 0..s[i] { + s.push(cur); } i += 1; } - s.as_bytes()[0..n].iter().filter(|&v| v == &b'1').count() as i32 + + s.iter().take(n as usize).filter(|&&x| x == 1).count() as i32 } } ``` diff --git a/solution/0400-0499/0481.Magical String/README_EN.md b/solution/0400-0499/0481.Magical String/README_EN.md index bad1c9afde676..f5afaf45c2973 100644 --- a/solution/0400-0499/0481.Magical String/README_EN.md +++ b/solution/0400-0499/0481.Magical String/README_EN.md @@ -56,7 +56,39 @@ tags: -### Solution 1 +### Solution 1: Simulate the Construction Process + +According to the problem, we know that each group of numbers in the string $s$ can be obtained from the digits of the string $s$ itself. + +The first two groups of numbers in string $s$ are $1$ and $22$, which are obtained from the first and second digits of string $s$, respectively. Moreover, the first group of numbers contains only $1$, the second group contains only $2$, the third group contains only $1$, and so on. + +Since the first two groups of numbers are known, we initialize string $s$ as $122$, and then start constructing from the third group. The third group of numbers is obtained from the third digit of string $s$ (index $i=2$), so at this point, we point the pointer $i$ to the third digit $2$ of string $s$. + +``` +1 2 2 + ^ + i +``` + +The digit pointed by pointer $i$ is $2$, indicating that the third group of numbers will appear twice. Since the previous group of numbers is $2$, and the numbers alternate between groups, the third group of numbers is two $1$s, i.e., $11$. After construction, the pointer $i$ moves to the next position, pointing to the fourth digit $1$ of string $s$. + +``` +1 2 2 1 1 + ^ + i +``` + +At this point, the digit pointed by pointer $i$ is $1$, indicating that the fourth group of numbers will appear once. Since the previous group of numbers is $1$, and the numbers alternate between groups, the fourth group of numbers is one $2$, i.e., $2$. After construction, the pointer $i$ moves to the next position, pointing to the fifth digit $1$ of string $s$. + +``` +1 2 2 1 1 2 + ^ + i +``` + +Following this rule, we simulate the construction process sequentially until the length of string $s$ is greater than or equal to $n$. + +The time complexity is $O(n)$, and the space complexity is $O(n)$. @@ -70,7 +102,6 @@ class Solution: while len(s) < n: pre = s[-1] cur = 3 - pre - # cur 表示这一组的数字,s[i] 表示这一组数字出现的次数 s += [cur] * s[i] i += 1 return s[:n].count(1) @@ -81,7 +112,7 @@ class Solution: ```java class Solution { public int magicalString(int n) { - List s = new ArrayList<>(Arrays.asList(1, 2, 2)); + List s = new ArrayList<>(List.of(1, 2, 2)); for (int i = 2; s.size() < n; ++i) { int pre = s.get(s.size() - 1); int cur = 3 - pre; @@ -144,17 +175,15 @@ func magicalString(n int) (ans int) { ```ts function magicalString(n: number): number { - const cs = [...'1221121']; - let i = 5; - while (cs.length < n) { - const c = cs[cs.length - 1]; - cs.push(c === '1' ? '2' : '1'); - if (cs[i] !== '1') { - cs.push(c === '1' ? '2' : '1'); + const s: number[] = [1, 2, 2]; + for (let i = 2; s.length < n; ++i) { + let pre = s[s.length - 1]; + let cur = 3 - pre; + for (let j = 0; j < s[i]; ++j) { + s.push(cur); } - i++; } - return cs.slice(0, n).reduce((r, c) => r + (c === '1' ? 1 : 0), 0); + return s.slice(0, n).filter(x => x === 1).length; } ``` @@ -163,18 +192,19 @@ function magicalString(n: number): number { ```rust impl Solution { pub fn magical_string(n: i32) -> i32 { - let n = n as usize; - let mut s = String::from("1221121"); - let mut i = 5; - while s.len() < n { - let c = s.as_bytes()[s.len() - 1]; - s.push(if c == b'1' { '2' } else { '1' }); - if s.as_bytes()[i] != b'1' { - s.push(if c == b'1' { '2' } else { '1' }); + let mut s = vec![1, 2, 2]; + let mut i = 2; + + while s.len() < n as usize { + let pre = s[s.len() - 1]; + let cur = 3 - pre; + for _ in 0..s[i] { + s.push(cur); } i += 1; } - s.as_bytes()[0..n].iter().filter(|&v| v == &b'1').count() as i32 + + s.iter().take(n as usize).filter(|&&x| x == 1).count() as i32 } } ``` diff --git a/solution/0400-0499/0481.Magical String/Solution.java b/solution/0400-0499/0481.Magical String/Solution.java index b2f3bf7486592..0a3b87d71f292 100644 --- a/solution/0400-0499/0481.Magical String/Solution.java +++ b/solution/0400-0499/0481.Magical String/Solution.java @@ -1,6 +1,6 @@ class Solution { public int magicalString(int n) { - List s = new ArrayList<>(Arrays.asList(1, 2, 2)); + List s = new ArrayList<>(List.of(1, 2, 2)); for (int i = 2; s.size() < n; ++i) { int pre = s.get(s.size() - 1); int cur = 3 - pre; diff --git a/solution/0400-0499/0481.Magical String/Solution.py b/solution/0400-0499/0481.Magical String/Solution.py index 6365fc7acc0ba..a96a04b1adce7 100644 --- a/solution/0400-0499/0481.Magical String/Solution.py +++ b/solution/0400-0499/0481.Magical String/Solution.py @@ -5,7 +5,6 @@ def magicalString(self, n: int) -> int: while len(s) < n: pre = s[-1] cur = 3 - pre - # cur 表示这一组的数字,s[i] 表示这一组数字出现的次数 s += [cur] * s[i] i += 1 return s[:n].count(1) diff --git a/solution/0400-0499/0481.Magical String/Solution.rs b/solution/0400-0499/0481.Magical String/Solution.rs index e9b0b628cb9c5..ed22f6f7303b9 100644 --- a/solution/0400-0499/0481.Magical String/Solution.rs +++ b/solution/0400-0499/0481.Magical String/Solution.rs @@ -1,16 +1,17 @@ impl Solution { pub fn magical_string(n: i32) -> i32 { - let n = n as usize; - let mut s = String::from("1221121"); - let mut i = 5; - while s.len() < n { - let c = s.as_bytes()[s.len() - 1]; - s.push(if c == b'1' { '2' } else { '1' }); - if s.as_bytes()[i] != b'1' { - s.push(if c == b'1' { '2' } else { '1' }); + let mut s = vec![1, 2, 2]; + let mut i = 2; + + while s.len() < n as usize { + let pre = s[s.len() - 1]; + let cur = 3 - pre; + for _ in 0..s[i] { + s.push(cur); } i += 1; } - s.as_bytes()[0..n].iter().filter(|&v| v == &b'1').count() as i32 + + s.iter().take(n as usize).filter(|&&x| x == 1).count() as i32 } } diff --git a/solution/0400-0499/0481.Magical String/Solution.ts b/solution/0400-0499/0481.Magical String/Solution.ts index e00acb97e0278..332dee40972f8 100644 --- a/solution/0400-0499/0481.Magical String/Solution.ts +++ b/solution/0400-0499/0481.Magical String/Solution.ts @@ -1,13 +1,11 @@ function magicalString(n: number): number { - const cs = [...'1221121']; - let i = 5; - while (cs.length < n) { - const c = cs[cs.length - 1]; - cs.push(c === '1' ? '2' : '1'); - if (cs[i] !== '1') { - cs.push(c === '1' ? '2' : '1'); + const s: number[] = [1, 2, 2]; + for (let i = 2; s.length < n; ++i) { + let pre = s[s.length - 1]; + let cur = 3 - pre; + for (let j = 0; j < s[i]; ++j) { + s.push(cur); } - i++; } - return cs.slice(0, n).reduce((r, c) => r + (c === '1' ? 1 : 0), 0); + return s.slice(0, n).filter(x => x === 1).length; } diff --git a/solution/0400-0499/0482.License Key Formatting/README.md b/solution/0400-0499/0482.License Key Formatting/README.md index b1fe1afd64be4..62fe28a11845e 100644 --- a/solution/0400-0499/0482.License Key Formatting/README.md +++ b/solution/0400-0499/0482.License Key Formatting/README.md @@ -57,7 +57,15 @@ tags: -### 方法一 +### 方法一:模拟 + +我们先统计出字符串 $s$ 中除去破折号之外的字符个数,并对 $k$ 取模,得到第一组字符的个数。如果为 $0$,则第一组字符个数为 $k$,否则为取模的结果。 + +接着我们遍历字符串 $s$,对于每个字符,如果是破折号,则跳过;否则将其转换为大写字母,并将其加入答案字符串中。同时,我们维护一个计数器 $cnt$,表示当前组还剩余的字符个数,当 $cnt$ 减为 $0$ 时,我们需要更新 $cnt$ 为 $k$,并且如果当前字符不是最后一个字符,我们需要在答案字符串中加入一个破折号。 + +最后,我们移除答案字符串末尾的破折号,并返回答案字符串。 + +时间复杂度 $O(n)$,其中 $n$ 为字符串 $s$ 的长度。忽略答案字符串的空间消耗,空间复杂度 $O(1)$。 @@ -66,19 +74,19 @@ tags: ```python class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: - s = s.replace('-', '').upper() - res = [] - cnt = (len(s) % k) or k - t = 0 + n = len(s) + cnt = (n - s.count("-")) % k or k + ans = [] for i, c in enumerate(s): - res.append(c) - t += 1 - if t == cnt: - t = 0 + if c == "-": + continue + ans.append(c.upper()) + cnt -= 1 + if cnt == 0: cnt = k - if i != len(s) - 1: - res.append('-') - return ''.join(res) + if i != n - 1: + ans.append("-") + return "".join(ans).rstrip("-") ``` #### Java @@ -86,25 +94,30 @@ class Solution: ```java class Solution { public String licenseKeyFormatting(String s, int k) { - s = s.replace("-", "").toUpperCase(); - StringBuilder sb = new StringBuilder(); - int t = 0; - int cnt = s.length() % k; + int n = s.length(); + int cnt = (int) (n - s.chars().filter(ch -> ch == '-').count()) % k; if (cnt == 0) { cnt = k; } - for (int i = 0; i < s.length(); ++i) { - sb.append(s.charAt(i)); - ++t; - if (t == cnt) { - t = 0; + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < n; i++) { + char c = s.charAt(i); + if (c == '-') { + continue; + } + ans.append(Character.toUpperCase(c)); + --cnt; + if (cnt == 0) { cnt = k; - if (i != s.length() - 1) { - sb.append('-'); + if (i != n - 1) { + ans.append('-'); } } } - return sb.toString(); + if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') { + ans.deleteCharAt(ans.length() - 1); + } + return ans.toString(); } } ``` @@ -115,26 +128,29 @@ class Solution { class Solution { public: string licenseKeyFormatting(string s, int k) { - string ss = ""; - for (char c : s) { - if (c == '-') continue; - if ('a' <= c && c <= 'z') c += 'A' - 'a'; - ss += c; + int n = s.length(); + int cnt = (n - count(s.begin(), s.end(), '-')) % k; + if (cnt == 0) { + cnt = k; } - int cnt = ss.size() % k; - if (cnt == 0) cnt = k; - int t = 0; - string res = ""; - for (int i = 0; i < ss.size(); ++i) { - res += ss[i]; - ++t; - if (t == cnt) { - t = 0; + string ans; + for (int i = 0; i < n; ++i) { + char c = s[i]; + if (c == '-') { + continue; + } + ans += toupper(c); + if (--cnt == 0) { cnt = k; - if (i != ss.size() - 1) res += '-'; + if (i != n - 1) { + ans += '-'; + } } } - return res; + if (!ans.empty() && ans.back() == '-') { + ans.pop_back(); + } + return ans; } }; ``` @@ -143,25 +159,54 @@ public: ```go func licenseKeyFormatting(s string, k int) string { - s = strings.ReplaceAll(s, "-", "") - cnt := len(s) % k + n := len(s) + cnt := (n - strings.Count(s, "-")) % k if cnt == 0 { cnt = k } - t := 0 - res := []byte{} - for i, c := range s { - res = append(res, byte(unicode.ToUpper(c))) - t++ - if t == cnt { - t = 0 + + var ans strings.Builder + for i := 0; i < n; i++ { + c := s[i] + if c == '-' { + continue + } + if cnt == 0 { cnt = k - if i != len(s)-1 { - res = append(res, byte('-')) - } + ans.WriteByte('-') } + ans.WriteRune(unicode.ToUpper(rune(c))) + cnt-- } - return string(res) + + return ans.String() +} +``` + +#### TypeScript + +```ts +function licenseKeyFormatting(s: string, k: number): string { + const n = s.length; + let cnt = (n - (s.match(/-/g) || []).length) % k || k; + const ans: string[] = []; + for (let i = 0; i < n; i++) { + const c = s[i]; + if (c === '-') { + continue; + } + ans.push(c.toUpperCase()); + if (--cnt === 0) { + cnt = k; + if (i !== n - 1) { + ans.push('-'); + } + } + } + while (ans.at(-1) === '-') { + ans.pop(); + } + return ans.join(''); } ``` diff --git a/solution/0400-0499/0482.License Key Formatting/README_EN.md b/solution/0400-0499/0482.License Key Formatting/README_EN.md index c8e3938a49aa5..55f3e9dfd8e24 100644 --- a/solution/0400-0499/0482.License Key Formatting/README_EN.md +++ b/solution/0400-0499/0482.License Key Formatting/README_EN.md @@ -55,7 +55,15 @@ Note that the two extra dashes are not needed and can be removed. -### Solution 1 +### Solution 1: Simulation + +First, we count the number of characters in the string $s$ excluding the hyphens, and take the modulus of $k$ to determine the number of characters in the first group. If it is $0$, then the number of characters in the first group is $k$; otherwise, it is the result of the modulus operation. + +Next, we iterate through the string $s$. For each character, if it is a hyphen, we skip it; otherwise, we convert it to an uppercase letter and add it to the answer string. Meanwhile, we maintain a counter $cnt$, representing the remaining number of characters in the current group. When $cnt$ decreases to $0$, we need to update $cnt$ to $k$, and if the current character is not the last one, we need to add a hyphen to the answer string. + +Finally, we remove the hyphen at the end of the answer string and return the answer string. + +The time complexity is $O(n)$, where $n$ is the length of the string $s$. Ignoring the space consumption of the answer string, the space complexity is $O(1)$. @@ -64,19 +72,19 @@ Note that the two extra dashes are not needed and can be removed. ```python class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: - s = s.replace('-', '').upper() - res = [] - cnt = (len(s) % k) or k - t = 0 + n = len(s) + cnt = (n - s.count("-")) % k or k + ans = [] for i, c in enumerate(s): - res.append(c) - t += 1 - if t == cnt: - t = 0 + if c == "-": + continue + ans.append(c.upper()) + cnt -= 1 + if cnt == 0: cnt = k - if i != len(s) - 1: - res.append('-') - return ''.join(res) + if i != n - 1: + ans.append("-") + return "".join(ans).rstrip("-") ``` #### Java @@ -84,25 +92,30 @@ class Solution: ```java class Solution { public String licenseKeyFormatting(String s, int k) { - s = s.replace("-", "").toUpperCase(); - StringBuilder sb = new StringBuilder(); - int t = 0; - int cnt = s.length() % k; + int n = s.length(); + int cnt = (int) (n - s.chars().filter(ch -> ch == '-').count()) % k; if (cnt == 0) { cnt = k; } - for (int i = 0; i < s.length(); ++i) { - sb.append(s.charAt(i)); - ++t; - if (t == cnt) { - t = 0; + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < n; i++) { + char c = s.charAt(i); + if (c == '-') { + continue; + } + ans.append(Character.toUpperCase(c)); + --cnt; + if (cnt == 0) { cnt = k; - if (i != s.length() - 1) { - sb.append('-'); + if (i != n - 1) { + ans.append('-'); } } } - return sb.toString(); + if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') { + ans.deleteCharAt(ans.length() - 1); + } + return ans.toString(); } } ``` @@ -113,26 +126,29 @@ class Solution { class Solution { public: string licenseKeyFormatting(string s, int k) { - string ss = ""; - for (char c : s) { - if (c == '-') continue; - if ('a' <= c && c <= 'z') c += 'A' - 'a'; - ss += c; + int n = s.length(); + int cnt = (n - count(s.begin(), s.end(), '-')) % k; + if (cnt == 0) { + cnt = k; } - int cnt = ss.size() % k; - if (cnt == 0) cnt = k; - int t = 0; - string res = ""; - for (int i = 0; i < ss.size(); ++i) { - res += ss[i]; - ++t; - if (t == cnt) { - t = 0; + string ans; + for (int i = 0; i < n; ++i) { + char c = s[i]; + if (c == '-') { + continue; + } + ans += toupper(c); + if (--cnt == 0) { cnt = k; - if (i != ss.size() - 1) res += '-'; + if (i != n - 1) { + ans += '-'; + } } } - return res; + if (!ans.empty() && ans.back() == '-') { + ans.pop_back(); + } + return ans; } }; ``` @@ -141,25 +157,54 @@ public: ```go func licenseKeyFormatting(s string, k int) string { - s = strings.ReplaceAll(s, "-", "") - cnt := len(s) % k + n := len(s) + cnt := (n - strings.Count(s, "-")) % k if cnt == 0 { cnt = k } - t := 0 - res := []byte{} - for i, c := range s { - res = append(res, byte(unicode.ToUpper(c))) - t++ - if t == cnt { - t = 0 + + var ans strings.Builder + for i := 0; i < n; i++ { + c := s[i] + if c == '-' { + continue + } + if cnt == 0 { cnt = k - if i != len(s)-1 { - res = append(res, byte('-')) - } + ans.WriteByte('-') } + ans.WriteRune(unicode.ToUpper(rune(c))) + cnt-- } - return string(res) + + return ans.String() +} +``` + +#### TypeScript + +```ts +function licenseKeyFormatting(s: string, k: number): string { + const n = s.length; + let cnt = (n - (s.match(/-/g) || []).length) % k || k; + const ans: string[] = []; + for (let i = 0; i < n; i++) { + const c = s[i]; + if (c === '-') { + continue; + } + ans.push(c.toUpperCase()); + if (--cnt === 0) { + cnt = k; + if (i !== n - 1) { + ans.push('-'); + } + } + } + while (ans.at(-1) === '-') { + ans.pop(); + } + return ans.join(''); } ``` diff --git a/solution/0400-0499/0482.License Key Formatting/Solution.cpp b/solution/0400-0499/0482.License Key Formatting/Solution.cpp index cd84af731406e..d3cfd34d1d359 100644 --- a/solution/0400-0499/0482.License Key Formatting/Solution.cpp +++ b/solution/0400-0499/0482.License Key Formatting/Solution.cpp @@ -1,25 +1,28 @@ class Solution { public: string licenseKeyFormatting(string s, int k) { - string ss = ""; - for (char c : s) { - if (c == '-') continue; - if ('a' <= c && c <= 'z') c += 'A' - 'a'; - ss += c; + int n = s.length(); + int cnt = (n - count(s.begin(), s.end(), '-')) % k; + if (cnt == 0) { + cnt = k; } - int cnt = ss.size() % k; - if (cnt == 0) cnt = k; - int t = 0; - string res = ""; - for (int i = 0; i < ss.size(); ++i) { - res += ss[i]; - ++t; - if (t == cnt) { - t = 0; + string ans; + for (int i = 0; i < n; ++i) { + char c = s[i]; + if (c == '-') { + continue; + } + ans += toupper(c); + if (--cnt == 0) { cnt = k; - if (i != ss.size() - 1) res += '-'; + if (i != n - 1) { + ans += '-'; + } } } - return res; + if (!ans.empty() && ans.back() == '-') { + ans.pop_back(); + } + return ans; } }; \ No newline at end of file diff --git a/solution/0400-0499/0482.License Key Formatting/Solution.go b/solution/0400-0499/0482.License Key Formatting/Solution.go index c4aad1e837e23..1318658c5cba6 100644 --- a/solution/0400-0499/0482.License Key Formatting/Solution.go +++ b/solution/0400-0499/0482.License Key Formatting/Solution.go @@ -1,21 +1,23 @@ func licenseKeyFormatting(s string, k int) string { - s = strings.ReplaceAll(s, "-", "") - cnt := len(s) % k + n := len(s) + cnt := (n - strings.Count(s, "-")) % k if cnt == 0 { cnt = k } - t := 0 - res := []byte{} - for i, c := range s { - res = append(res, byte(unicode.ToUpper(c))) - t++ - if t == cnt { - t = 0 + + var ans strings.Builder + for i := 0; i < n; i++ { + c := s[i] + if c == '-' { + continue + } + if cnt == 0 { cnt = k - if i != len(s)-1 { - res = append(res, byte('-')) - } + ans.WriteByte('-') } + ans.WriteRune(unicode.ToUpper(rune(c))) + cnt-- } - return string(res) + + return ans.String() } \ No newline at end of file diff --git a/solution/0400-0499/0482.License Key Formatting/Solution.java b/solution/0400-0499/0482.License Key Formatting/Solution.java index 8aebd76c699cc..6438f4c5948b3 100644 --- a/solution/0400-0499/0482.License Key Formatting/Solution.java +++ b/solution/0400-0499/0482.License Key Formatting/Solution.java @@ -1,23 +1,28 @@ class Solution { public String licenseKeyFormatting(String s, int k) { - s = s.replace("-", "").toUpperCase(); - StringBuilder sb = new StringBuilder(); - int t = 0; - int cnt = s.length() % k; + int n = s.length(); + int cnt = (int) (n - s.chars().filter(ch -> ch == '-').count()) % k; if (cnt == 0) { cnt = k; } - for (int i = 0; i < s.length(); ++i) { - sb.append(s.charAt(i)); - ++t; - if (t == cnt) { - t = 0; + StringBuilder ans = new StringBuilder(); + for (int i = 0; i < n; i++) { + char c = s.charAt(i); + if (c == '-') { + continue; + } + ans.append(Character.toUpperCase(c)); + --cnt; + if (cnt == 0) { cnt = k; - if (i != s.length() - 1) { - sb.append('-'); + if (i != n - 1) { + ans.append('-'); } } } - return sb.toString(); + if (ans.length() > 0 && ans.charAt(ans.length() - 1) == '-') { + ans.deleteCharAt(ans.length() - 1); + } + return ans.toString(); } } \ No newline at end of file diff --git a/solution/0400-0499/0482.License Key Formatting/Solution.py b/solution/0400-0499/0482.License Key Formatting/Solution.py index 9f4445b2f489c..6c069c9d1b304 100644 --- a/solution/0400-0499/0482.License Key Formatting/Solution.py +++ b/solution/0400-0499/0482.License Key Formatting/Solution.py @@ -1,15 +1,15 @@ class Solution: def licenseKeyFormatting(self, s: str, k: int) -> str: - s = s.replace('-', '').upper() - res = [] - cnt = (len(s) % k) or k - t = 0 + n = len(s) + cnt = (n - s.count("-")) % k or k + ans = [] for i, c in enumerate(s): - res.append(c) - t += 1 - if t == cnt: - t = 0 + if c == "-": + continue + ans.append(c.upper()) + cnt -= 1 + if cnt == 0: cnt = k - if i != len(s) - 1: - res.append('-') - return ''.join(res) + if i != n - 1: + ans.append("-") + return "".join(ans).rstrip("-") diff --git a/solution/0400-0499/0482.License Key Formatting/Solution.ts b/solution/0400-0499/0482.License Key Formatting/Solution.ts new file mode 100644 index 0000000000000..0401dd62acdae --- /dev/null +++ b/solution/0400-0499/0482.License Key Formatting/Solution.ts @@ -0,0 +1,22 @@ +function licenseKeyFormatting(s: string, k: number): string { + const n = s.length; + let cnt = (n - (s.match(/-/g) || []).length) % k || k; + const ans: string[] = []; + for (let i = 0; i < n; i++) { + const c = s[i]; + if (c === '-') { + continue; + } + ans.push(c.toUpperCase()); + if (--cnt === 0) { + cnt = k; + if (i !== n - 1) { + ans.push('-'); + } + } + } + while (ans.at(-1) === '-') { + ans.pop(); + } + return ans.join(''); +}