题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
using System;
using System.Collections.Generic;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串一维数组
*/
public List<string> restoreIpAddresses (string s) {
List<string> res = new List<string>();
if(s.Length > 12) return res;
if(s.Length < 4) return res;
for(int i = 1; i < 5; i++){
for(int j = 1; j < 5; j++){
for(int k = 1; k < 5; k++){
if(i + j + k >= s.Length) continue;
if(i + j + k < s.Length - 4) continue;
string a = s.Substring(0, i);
string b = s.Substring(i, j);
string c = s.Substring(i + j, k);
string d = s.Substring(i + j + k, s.Length - i - k - j);
if(Int32.Parse(a) > 255 || Int32.Parse(b) > 255 || Int32.Parse(c) > 255 || Int32.Parse(d) > 255) continue;
if((a.Length != 1 && a[0] == '0') || (b.Length != 1 && b[0] == '0') || (c.Length != 1 && c[0] == '0') || (d.Length != 1 && d[0] == '0')) continue;
String temp = a + "." + b + "." + c + "." + d;
res.Add(temp);
}
}
}
return res;
}
}
