问题描述
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”]
问题分析
经验教训
这类题目的难点之处就在于如何找递归关系,如何设计递归函数,以及递归终止条件的确定
代码实现
class Solution {
public List<String> restoreIpAddresses(String s) {
if (s == null ) {
return new ArrayList<String>();
}
char [] chs = s.toCharArray();
StringBuilder ip = new StringBuilder();
ArrayList<String> res = new ArrayList<>();
findIp(chs, ip, 0 , 0 , res);
return res;
}
public void findIp(char [] chs, StringBuilder ip, int i, int sectionNum, ArrayList<String> res) {
if (i == chs.length || sectionNum == 4 ) {
if (sectionNum == 4 && i == chs.length) {
res.add(ip.toString());
}
return ;
}
int length = ip.length();
for (int k = i; k < chs.length && k < i + 3 ; k++) {
String str = new String(chs, i, k - i + 1 );
if (isValid(str )) {
ip = sectionNum == 3 ? ip.append(str ) : ip.append(str ).append("." );
findIp(chs, ip, k + 1 , sectionNum + 1 , res);
ip.setLength(length);
}
}
return ;
}
public boolean isValid(String str ) {
if (str .length() > 1 && str .charAt(0 ) - '0' == 0 ) {
return false ;
}
return Integer.valueOf(str ) <= 255 ;
}
}