You are given a license key represented as a string S which consists of only alphanumeric characters and dashes. The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Example:
Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
Approach:
C++
#include <bits/stdc++.h>using namespace std;string licenseKeyFormatting(string S, int K){int n = S.size();string res = "";int cnt = 0;vector<char> v;for (int i = 0; i < n; i++)if (S[i] != '-')v.push_back(S[i]);if (v.size() == 0)return res;for (int i = 0; i < v.size(); i++)if (v[i] >= 'a' && v[i] <= 'z')v[i] = v[i] - 32;for (int i = v.size() - 1; i >= 0; i--){res += v[i];cnt++;if (cnt == K){cnt = 0;res += '-';}}if (res[res.size() - 1] == '-')res.erase(res.begin() + res.size() - 1);reverse(res.begin(), res.end());return res;}int main(){string S = "5F3Z-2e-9-w";int K = 4;cout << licenseKeyFormatting(S, K);return 0;}
No comments:
Post a Comment