For example:
Given
"25525511135"
,
return
["255.255.11.135", "255.255.111.35"]
. (Order does not matter)public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
ArrayList<String> ret = new ArrayList<String>();
if(s==null) {
return ret;
}
int[] ips = new int[4];
helper(ret, s, 0, ips, 0);
return ret;
}
public void helper(ArrayList<String> ret, String s, int k, int ips[], int seg) {
if(seg==4) {
if(k==s.length()) {
ret.add(build(ips));
}
return;
}
if(k+1<=s.length()) {
ips[seg] = Integer.parseInt(s.substring(k, k+1));
helper(ret, s, k+1, ips, seg+1);
}
if(k+2<=s.length()) {
ips[seg] = Integer.parseInt(s.substring(k, k+2));
if(ips[seg]>=10) {
helper(ret, s, k+2, ips, seg+1);
}
}
if(k+3<=s.length()) {
ips[seg] = Integer.parseInt(s.substring(k, k+3));
if(ips[seg]<=255 && ips[seg]>=100) {
helper(ret, s, k+3, ips, seg+1);
}
}
}
public String build(int ips[]) {
StringBuilder sb = new StringBuilder();
sb.append(ips[0]).append('.').append(ips[1]).append('.').append(ips[2]).append('.').append(ips[3]);
return sb.toString();
}
}
=======
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
for (int i = 1; i < 4 && i < s.length() - 2; i++) {
for (int j = i + 1; j < i + 4 && j < s.length() - 1; j++) {
for (int k = j + 1; k < j + 4 && k < s.length(); k++) {
String s1 = s.substring(0, i);
String s2 = s.substring(i, j);
String s3 = s.substring(j, k);
String s4 = s.substring(k);
if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)) {
res.add(s1 + "." + s2 + "." + s3 + "." + s4);
}
}
}
}
return res;
}
private boolean isValid(String s) {
if (s.isEmpty()) {
return false;
}
if (s.length() == 1 || (s.length() == 2 && Integer.parseInt(s) >= 10) || (s.length() == 3 && Integer.parseInt(s) >= 100 && Integer.parseInt(s) <= 255)) {
return true;
} return false;
}
}
没有评论:
发表评论