题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
/*
大致思路:先将两个字符串合并,然后按照奇数和偶数位置放入两个数组,对两个数组分别排序后再合并,然后对合并后的字符串的每个字符按要求转换即可
*/
#include <cctype>
#include <iostream>
#include <vector>
#include <bitset>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int QuickSortPivot(vector<char> &arr, int start, int end){
int pivot = start;
int j = start + 1;
for(int i = start + 1; i <= end; i++){
if(arr[i] <= arr[pivot]){
swap(arr[i], arr[j]);
j++;
}
}
swap(arr[pivot], arr[j-1]);
pivot = j - 1;
return pivot;
}
void QuickSort(vector<char> &arr, int start, int end){
if(start >= end){
return;
}
int pivot = QuickSortPivot(arr, start, end);
QuickSort(arr, start, pivot-1);
QuickSort(arr, pivot+1, end);
}
string Hextobinary(char x) {
// 将十六进制字符转换为对应的整数
int num = (x >= '0' && x <= '9') ? x - '0' : x - 'A' + 10;
// 使用bitset<4>存储4位二进制
bitset<4> binary(num);
// 将bitset转换为字符串
string binaryStr = binary.to_string();
return binaryStr;
}
string binarytoHex(const string& binary){
bitset<32> binarySet(binary); // 假设二进制字符串不会超过32位
unsigned long int num = binarySet.to_ulong();
// 使用std::stringstream进行格式化输出为16进制
stringstream hexStream;
hexStream << hex << num; // 使用hex格式化标志
// 获取16进制字符串
string hexStr = hexStream.str();
return hexStr;
}
string trans(string s){
string ans = "";
for(char c : s){
if((c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f') || (c >= '0' && c <= '9')){
string htb = Hextobinary(c);
reverse(htb.begin(), htb.end());
string bth = binarytoHex(htb);
for(auto &v : bth){
if(isalpha(v))
v = toupper(v);
}
ans += bth;
}
else{
ans += c;
}
}
return ans;
}
int main() {
string s1, s2;
cin >> s1;
cin >> s2;
string s = s1 + s2;
vector<char> arr_j;
vector<char> arr_o;
for(int i = 0; i < s.size(); i++){
if(i % 2 == 0){
arr_o.push_back(s[i]);
}
else{
arr_j.push_back(s[i]);
}
}
QuickSort(arr_j, 0, arr_j.size()-1);
QuickSort(arr_o, 0, arr_o.size()-1);
string tmp = "";
int len = s.size();
int pos = 0;
int i = 0, j = 0;
while(pos < len){
if(pos % 2 == 0){
tmp += arr_o[i++];
}
else{
tmp += arr_j[j++];
}
pos++;
}
//cout << tmp << endl;
string res = trans(tmp);
cout << res << endl;
}
曼迪匹艾公司福利 124人发布