《递归回溯》求一个数字字符串的所有合法的IP地址

在这里插入图片描述
做一下这道题目,上次面试现场问到了,没回答出来,也是sb了。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;

[ExecuteInEditMode]
public class MathfTest : MonoBehaviour
{
    public long num;
    private List<List<string>> result = new List<List<string>>();
    private string[] tmpStr = new string[4] { "", "", "", "" };
    public void OnEnable()
    {
        result.Clear();
        if (num > 0)
        {
            string numStr = num.ToString();
            int size = numStr.Length;
            if (size < 4 || size > 12) return;
            int id = 0;
            Dfs(numStr, 0, ref id);
            if (result.Count > 0)
            {
                for (int i = 0; i < result.Count; i++)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < result[i].Count; j++)
                    {
                        sb.Append(result[i][j]);
                        if (j < result[i].Count - 1)
                        {
                            sb.Append(".");
                        }
                    }
                    Debug.LogError(sb.ToString());
                }
            }
        }
    }
    private bool IsOK(int id)
    {
        if (tmpStr[id].Length <= 0 || tmpStr[id].Length > 3)
        {
            return false;
        }
        int.TryParse(tmpStr[id], out int num);
        if (num < 0 || num > 255)
        {
            return false;
        }
        return true;
    }
    private void Dfs(string str, int bi, ref int id)
    {
        tmpStr[id] = "";
        int i = bi;
        for (; i < str.Length; i++)
        {
            tmpStr[id] += str[i];
            if (!IsOK(id))
            {
                return;
            }
            else
            {
                if (id < 3)
                {
                    ++id;
                    Dfs(str, i + 1, ref id);
                    tmpStr[id] = "";
                    --id;
                }
                else
                {
                    if (i == str.Length - 1)
                    {
                        result.Add(new List<string>() {
                            tmpStr[0],
                            tmpStr[1],
                            tmpStr[2],
                            tmpStr[3]
                        });
                    }
                }
            }
        }
    }
}

leetcode 原体
https://leetcode-cn.com/problems/restore-ip-addresses/solution/fu-yuan-ipdi-zhi-by-leetcode-solution/

这里对于0的考虑我忽略了
时间复杂度。

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JustEasyCode

谢谢您

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值