题目描述
题目难度:Medium
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
- Example:
Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]
AC代码
leetcode 一位大神的代码,和我思路一致,但是他的实现更细致,更优雅
https://leetcode.com/problems/restore-ip-addresses/discuss/251206/0ms-java-solution
note:1.01.02.1 不是合法的ip地址,也就是说数字不可以以0开头,除了0之外。
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> ans = new ArrayList();
if (s.length() > 3 && s.length() < 13) //预判断
help(s, new char[s.length()+3], 0, ans, 0, 0);
return ans;
}
/**
s:原s
cs:存放ip的数组
count:ip由 A.B.C.D 四部分组成,count 表示cs中现有ip部分的个数
ans:返回值
start:s中正在遍历的开始位置
i:cs中下一个存放字符位置的下标
*/
void help(String s, char[] cs, int count, List<String> ans, int start, int i){
int digit = 0;
for (int l = start; l < 3+start && l < s.length(); l++){ //ip的一个部分最多由三个数字构成,同时还要保证l没有超出s的范围
digit = 10*digit + (s.charAt(l)-'0');
if (digit > 255) return;
cs[i++] = s.charAt(l);
if (count == 3){ //之前已经存在ip的三部分
if (l+1==s.length()) ans.add(new String(cs)); //l已经到了s的末尾
}else{
cs[i] = '.';
help(s, cs, count+1, ans, l+1, i+1);
}
if (digit == 0) return; //这一步挺关键的,为了防止ip一部分的值类似于 01,010的存在
}
}
}