fg
2025-07-14 19:06:03
发布于:浙江
6阅读
0回复
0点赞
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string removeLeadingZeros(const string &group) {
string result = group;
result.erase(0, min(result.find_first_not_of('0'), result.size() - 1));
return result;
}
int main() {
string ipv6;
cin >> ipv6;
vector<string> groups;
stringstream ss(ipv6);
string group;
while (getline(ss, group, ':')) {
groups.push_back(group);
}
for (int i = 0; i < groups.size(); ++i) {
groups[i] = removeLeadingZeros(groups[i]);
}
int maxZeroCount = 0;
int currentZeroCount = 0;
int zeroStartIndex = -1;
int bestZeroStartIndex = -1;
for (int i = 0; i < groups.size(); ++i) {
if (groups[i].empty()) {
if (currentZeroCount == 0) {
zeroStartIndex = i;
}
currentZeroCount++;
} else {
if (currentZeroCount > maxZeroCount) {
maxZeroCount = currentZeroCount;
bestZeroStartIndex = zeroStartIndex; }
currentZeroCount = 0;
}
}
if (currentZeroCount > maxZeroCount) {
maxZeroCount = currentZeroCount;
bestZeroStartIndex = zeroStartIndex;
}
string result;
for (int i = 0; i < groups.size(); ++i) {
if (i == bestZeroStartIndex) {
result += "::";
i += maxZeroCount - 1;
} else {
if (!groups[i].empty() || (result.empty() && i == 0)) { // 处理前导冒号
if (!result.empty()) {
result += ":";
}
result += groups[i];
}
}
}
cout << result << endl;
return 0;
}
这里空空如也
有帮助,赞一个