#P2815. IPv6地址压缩
IPv6地址压缩
Description
[IPv6 Format]
In binary, an IPv6 address is bits long. It is divided into groups of bits, separated by colons “:”, making groups in total. Each group is written as a 4-digit hexadecimal number.
For example, 2001:0db8:0000:0000:0123:4567:89ab:cdef is a valid IPv6 address.
IPv6 addresses can be compressed under certain conditions:
- Leading zeros in each group can be omitted.
For example, the address above can be compressed to 2001:db8:0:0:123:4567:89ab:cdef.
- A double colon
::can represent one or more consecutive groups of0, but it can only appear once.
For example, the address above can be compressed to 2001:db8::123:4567:89ab:cdef.
Please help the forgetful network engineer Xiaoming solve his problem.
[Supplementary Rules]
-
The input is a fully expanded IPv6 address. It is guaranteed that the input IPv6 address contains no double colon, and that any omitted zeros in each group have been filled.
-
Since
::can be used only once, compress the longest run of all-zero groups.
For example, 2001:0db8:0000:0000:1:0000:0000:0000 is compressed to 2001:db8:0:0:1::, not 2001:db8::1:0:0:0.
- Since
::can be used only once, if there are multiple runs of all-zero groups with the same maximum length, compress the earliest one.
For example, 2001:0db8:0000:0000:ffff:0000:0000:1 is compressed to 2001:db8::ffff:0:0:1, not 2001:db8:0:0:ffff::1.
- The input IPv6 address may not be compressible. In that case, output it as-is.
Tip: The compression rules shown in this problem match the default IPv6 display style on macOS (Darwin), whereas Windows and Linux do not use :: when there is only a single all-zero group. However, IPv6 addresses compressed in this way can still be correctly recognized by Windows and Linux.
For example, 2001:0db8:ffff:0000:0123:4567:89ab:cdef is compressed by Darwin as 2001:db8:ffff::123:4567:89ab:cdef, while Linux and Windows compress it as 2001:db8:ffff:0:123:4567:89ab:cdef.
Input Format
A string of characters representing a fully expanded IPv6 address.
Output Format
A string representing the compressed IPv6 address.
2406:0840:f990:0000:0000:0000:0000:0001
2406:840:f990::1
2a13:1801:018a:00cf:0100:0000:0000:0000
2a13:1801:18a:cf:100::
2001:4860:4860:0000:0000:0000:0000:8888
2001:4860:4860::8888
2001:0db8:0000:0000:0000:0000:0000:0001
2001:db8::1
0000:0000:0000:0000:0000:0000:0000:0000
::
0000:0000:0000:0000:0000:0000:0000:0001
::1
2001:0db8:ffff:0000:0123:4567:89ab:cdef
2001:db8:ffff::123:4567:89ab:cdef
1234:5678:9abc:def0:1234:5678:9abc:def0
1234:5678:9abc:def0:1234:5678:9abc:def0
0001:0000:0000:0000:0000:0000:0000:0001
1::1
0000:0000:0000:0000:0000:0000:0001:0002
::1:2
Hint
Translated by ChatGPT 5
京公网安备 11011102002149号