题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
package main import "fmt" import "strings" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串一维数组 */ func dfsToFindValidIp(res *[]string, i int, s string, curIpSeq []string) { if len(curIpSeq) == 4 && i == len(s) { *res = append(*res, strings.Join(curIpSeq, ".")) return } //判断剩余的部分能不能组成一个序列 if len(curIpSeq) == 4 && i != len(s) || i == len(s) && len(curIpSeq) != 4 { return } //当前数字组成的序列 dfsToFindValidIp(res, i+1, s, append(curIpSeq, fmt.Sprintf("%c", s[i]))) if s[i] == '0' { return } if i+1 < len(s) { //两个字段组合看 dfsToFindValidIp(res, i+2, s, append(curIpSeq, fmt.Sprintf("%c%c", s[i], s[i+1]))) } if i+2 < len(s) { //三个字段组成的序列是否满足要求 tmpSeg := fmt.Sprintf("%c%c%c", s[i], s[i+1], s[i+2]) if tmpSeg <= "255" { dfsToFindValidIp(res, i+3, s, append(curIpSeq, tmpSeg)) } } } func restoreIpAddresses(s string) []string { // write code here /* "25525522135" "1111" "000256" */ res := make([]string, 0) dfsToFindValidIp(&res, 0, s, make([]string, 0)) return res }