讨论/技术交流/IPV6简化写法字符串还原为完整写法字符串/
IPV6简化写法字符串还原为完整写法字符串

简介

实现将ipv6简化表示的字符串还原为标准写法字符串。
例如:
2409:8900::1:231:3a4
还原后 2409:8900:0000:0000:0000:0001:0231:03a4

2409:8900:3:2:1211:1:22:643a
还原后2409:8900:0003:0002:1211:0001:0022:643a

要求在时间复杂度O(N)内。

共 1 个回复

有问题或者改进的话欢迎评论~

class Solution:
    def recoverIPv6(self, shortenedIPv6: str) -> str:
        splitResult = shortenedIPv6.split(':')
        i = 1
        while i < len(splitResult):
            if splitResult[i] == splitResult[i - 1] == '':
                del splitResult[i]
            else:
                i += 1
        originIPv6 = str()
        for result in splitResult:
            if result != '':
                originIPv6 += '0' * (4 - len(result)) + result + ':'
            else:
                for _ in range(8 - len(splitResult) + 1):
                    originIPv6 += '0' * 4 + ':'
        return originIPv6[:-1]


s = Solution()
assert (s.recoverIPv6('2409:8900::1:231:3a4') == '2409:8900:0000:0000:0000:0001:0231:03a4')
assert (s.recoverIPv6('2409:8900:3:2:1211:1:22:643a') == '2409:8900:0003:0002:1211:0001:0022:643a')
assert (s.recoverIPv6('2001:db8::ff00:42:8329') == '2001:0db8:0000:0000:0000:ff00:0042:8329')
assert (s.recoverIPv6('::1') == '0000:0000:0000:0000:0000:0000:0000:0001')
assert (s.recoverIPv6('::') == '0000:0000:0000:0000:0000:0000:0000:0000')
assert (s.recoverIPv6('ff02::1') == 'ff02:0000:0000:0000:0000:0000:0000:0001')
assert (s.recoverIPv6('fe80::a299:9bff:fe18:50d1') == 'fe80:0000:0000:0000:a299:9bff:fe18:50d1')
assert (s.recoverIPv6('2001:db8:1111:a:b0::200') == '2001:0db8:1111:000a:00b0:0000:0000:0200')
assert (s.recoverIPv6('2001:db8::abcd:0:0:1234') == '2001:0db8:0000:0000:abcd:0000:0000:1234')
assert (s.recoverIPv6('2001:db8:aaaa:1::100') == '2001:0db8:aaaa:0001:0000:0000:0000:0100')
assert (s.recoverIPv6('2001:db8:aaaa:1::200') == '2001:0db8:aaaa:0001:0000:0000:0000:0200')