Select solution language
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int INF = 1e9;
void solve1(string s) {
int n = s.size();
if (n == 0) return;
int cnt = 1;
for (int i = 1; i < n; i++) {
if (s[i] == s[i - 1]) {
cnt++;
} else {
cout << cnt << s[i - 1];
cnt = 1;
}
}
cout << cnt << s[n - 1];
}
void solve2(string s){
int n = s.size();
string res = "";
for(int i = 0; i < n; i++){
int cnt = 0;
while(i < n && isdigit(s[i])){
cnt = cnt * 10 + (s[i] - '0');
i++;
}
if(i < n && isalpha(s[i])){
res += string(cnt, s[i]);
}
}
cout << res;
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
string s1, s2;
cin >> s1 >> s2;
solve1(s1);
cout << endl;
solve2(s2);
return 0;
}
Code mẫu:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int INF = 1e9;
void solve1(string s){
int n = s.size();
unordered_map<char, int> mp;
for(char c : s) mp[c]++;
unordered_set<int> pr;
for(char c : s){
if(pr.find(c) == pr.end()){
cout << mp[c] << c;
pr.insert(c);
}
}
}
void solve2(string s){
int n = s.size();
string res = "";
for(int i = 0; i < n; i++){
int cnt = 0;
while(i < n && isdigit(s[i])){
cnt = cnt * 10 + (s[i] - '0');
i++;
}
if(i < n && isalpha(s[i])){
res += string(cnt, s[i]);
}
}
cout << res;
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
string s1, s2;
cin >> s1 >> s2;
solve1(s1);
cout << endl;
solve2(s2);
return 0;
}
Đầu tiên ta phân tích đầu vào của hệ thống, nhận thấy ta cần sử dụng hai hàm để giải quyết hai vấn đề (mã hóa và giải mã) > Với mã hóa
def mahoa(x):
last = x[0] # kí tự đầu tiên giống
count = 0 # đếm số kí tự thỏa mãn
s = "" # một xâu rỗng để thêm kết quả
for i in x:
if i == last: # nếu kí tự này vẫn nằm trong một chuỗi liên tiếp
count += 1
else:
s = s + str(count) + last # thêm số và kí tự vào đáp án
last = i; # Khởi tạo biến lại như ban đầu
count = 1 # Tại vì mình set cả kí tự này nên sẽ đếm từ 1
s = s + str(count) + last # thêm vào đáp án chuỗi kí tự giống nhau cuối cùng
return s
> Với giải mã
def giaima(x):
number = ""
s = ""
for i in x:
if "0" <= i <= "9": # kiểm tra xem có phải chữ số / thêm vào để tạo thành số hoàn chỉnh
number += i
else:
s = s + i*int(number) # in ra kết quả dựa theo chữ số và số đã set
number = ""
return s;