Topic describes
This is 482 on LeetCode. Key formatting is easy.
Tag: “Simulation”
There is a key string S that contains only letters, numbers, and ‘-‘ (dashes). Where N ‘-‘ divides the string into N+1 groups.
Given a number K, reformat the string so that each grouping contains exactly K characters. In particular, the first group must contain less than or equal to K characters, but at least 1 character. The two groups need to be separated by a ‘-‘ (dash) and all lowercase letters need to be converted to uppercase letters.
Given a non-empty string S and a number K, format according to the rules described above.
Example 1:
Input: S = "5f3z-2e-9-w ", K = 4 Output:" 5F3Z-2e9w "Explanation: The string S is split into two parts, each of which contains four characters; Note that the two extra dashes need to be deleted.Copy the code
Example 2:
Input: S = "2-5g-3-j ", K = 2 Output:" 2-5g-3j"Copy the code
Tip:
- The length of S may be very long, please allocate the size according to need. K is a positive integer.
- The S contains only alphanumeric characters (A-z, A-z, 0-9) and dashes (‘-‘).
- S is not empty
simulation
Simple string simulation, from the back to the front, to avoid the first partition of the case of the discussion and mod operation.
Code:
class Solution {
public String licenseKeyFormatting(String s, int k) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1, cnt = 0; i >= 0; i--) {
if (s.charAt(i) == The '-') continue;
if (cnt == k && (cnt = 0) > =0) sb.append("-");
sb.append(s.charAt(i));
cnt++;
}
returnsb.reverse().toString().toUpperCase(); }}Copy the code
- Time complexity: O(n)O(n)O(n)
- Space complexity: O(n)O(n)O(n)
The last
This is the No.482 of our “Brush through LeetCode” series, which started on 2021/01/01. There are 1916 topics in LeetCode as of the start date, some of which have locks.
In this series of articles, in addition to explaining how to solve the problem, I will also present the most concise code possible. If a general solution is involved, the corresponding code template will also be used.
In order to facilitate the students to debug and submit the code on the computer, I set up the relevant warehouse: github.com/SharingSour… .
In the repository, you’ll see links to the series of articles, the corresponding code for the series of articles, the LeetCode source links, and other preferred solutions.