Skip to content

Instantly share code, notes, and snippets.

@Desolve
Created January 6, 2020 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/1ae57afd061a562a0eab62b379fed9b4 to your computer and use it in GitHub Desktop.
Save Desolve/1ae57afd061a562a0eab62b379fed9b4 to your computer and use it in GitHub Desktop.
0093 Restore IP Addresses
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new LinkedList<String>();
checkIP(s, res, 0, 0, "");
return res;
}
private void checkIP(String s, List<String> res, int i, int cnt, String cur) {
if (s.length() - i < 4 - cnt) return;
if (cnt == 3) {
if (s.length() - i <= 3) {
if (s.charAt(i) != '0' && Integer.parseInt(s.substring(i)) <= 255 || s.substring(i).equals("0")) {
cur += s.substring(i);
res.add(cur);
}
}
} else {
for (int j = 1; j <= 3 && i + j <= s.length(); ++j) {
if (s.charAt(i) != '0' && Integer.parseInt(s.substring(i, i + j)) <= 255 || s.substring(i, i + j).equals("0")) {
checkIP(s, res, i + j, cnt + 1, cur + s.substring(i, i + j) + ".");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment