暴力打表90分求助
查看原帖
暴力打表90分求助
206814
封禁用户楼主2022/10/27 20:46

我这个解法属实有点暴力,跟样例对没问题,求调,谢谢.

#include <bits/stdc++.h>
using namespace std;
const char* zero[] ={
    "0000:0000:0000:0000:0000:0000:0000:0000", //8
    "0000:0000:0000:0000:0000:0000:0000", //7
    "0000:0000:0000:0000:0000:0000", //6
    "0000:0000:0000:0000:0000", //5
    "0000:0000:0000:0000", //4
    "0000:0000:0000", //3
    "0000:0000", //2
    "0000" //1
};
string ipv6;
int main(){
    int i = 0, pos = 0;
    cin >> ipv6;
    while(i < 8 && (pos = ipv6.find(zero[i])) == string::npos) i++;
    if(i == 0){
        cout << "::" << endl;
        return 0;
    }
    if(pos != string::npos){
        if(pos + strlen(zero[i]) == ipv6.length()) ipv6 = ipv6.substr(0, pos) + ":";
        else if(pos == 0) ipv6 = ":" + ipv6.substr(strlen(zero[i]), ipv6.length() - strlen(zero[i]) + 1);
        else ipv6 = ipv6.substr(0, pos) + ipv6.substr(pos + strlen(zero[i]), ipv6.length() - (pos + strlen(zero[i])) + 1);
    }
    for(int i = 0; i < ipv6.length();){
        while(ipv6[i] == '0') i++;
        if(ipv6[i] == ':' && ipv6[i + 1] != ':' && ipv6[i - 1] != ':') putchar('0');
        while(i < ipv6.length() && ipv6[i] != ':') putchar(ipv6[i]), i++;
        if(i != ipv6.length()) putchar(':'), i++;
    }
    return 0;
}
2022/10/27 20:46
加载中...