做一下这道题目,上次面试现场问到了,没回答出来,也是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的考虑我忽略了
时间复杂度。