📑 题目:93. 复原 IP 地址

🚀 本题 LeetCode 传送门

题目大意

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

解题思路

  • DFS 深搜
  • 需要注意的点是 IP 的规则,以 0 开头的数字和超过 255 的数字都为非法的。

代码

  1. package leetcode
  2. import (
  3. ""strconv""
  4. )
  5. func restoreIPAddresses(s string) []string {
  6. if s == """" {
  7. return []string{}
  8. }
  9. res, ip := []string{}, []int{}
  10. dfs(s, 0, ip, &res)
  11. return res
  12. }
  13. func dfs(s string, index int, ip []int, res *[]string) {
  14. if index == len(s) {
  15. if len(ip) == 4 {
  16. *res = append(*res, getString(ip))
  17. }
  18. return
  19. }
  20. if index == 0 {
  21. num, _ := strconv.Atoi(string(s[0]))
  22. ip = append(ip, num)
  23. dfs(s, index+1, ip, res)
  24. } else {
  25. num, _ := strconv.Atoi(string(s[index]))
  26. next := ip[len(ip)-1]*10 + num
  27. if next <= 255 && ip[len(ip)-1] != 0 {
  28. ip[len(ip)-1] = next
  29. dfs(s, index+1, ip, res)
  30. ip[len(ip)-1] /= 10
  31. }
  32. if len(ip) < 4 {
  33. ip = append(ip, num)
  34. dfs(s, index+1, ip, res)
  35. ip = ip[:len(ip)-1]
  36. }
  37. }
  38. }
  39. func getString(ip []int) string {
  40. res := strconv.Itoa(ip[0])
  41. for i := 1; i < len(ip); i++ {
  42. res += ""."" + strconv.Itoa(ip[i])
  43. }
  44. return res
  45. }