For example:
Given
"25525511135"
,
return
["255.255.11.135", "255.255.111.35"]
. (Order does not matter)---
Solution: Use a recursive combinatorial algorithm. Whenever the last added character was not a dot, add a dot. Whenever the last added character was zero, and the current number is zero, then return because we cannot have anything after a leading zero. For numbers, add it only if it will keep the current number less than or equal to 255.
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
restore(list, sb, s, 0, 0, 0);
return list;
}
private void restore(List<String> list, StringBuilder sb, String s, int index, int word, int curNum) {
if (index == s.length() && word == 3 && sb.charAt(sb.length() - 1) != '.') {
list.add(sb.toString());
}
if (index >= s.length() || word > 3) {
return;
}
if (sb.length() > 0) {
int prev = sb.charAt(sb.length() - 1);
// Add dot whenever possible.
if (prev != '.') {
sb.append('.');
restore(list, sb, s, index, word + 1, 0);
sb.setLength(sb.length() - 1);
}
// If last digit was already zero, then cannot double-up on zeros.
if (curNum == 0 && prev == '0') {
return;
}
}
// Add next digit to current number if within range.
int ch = s.charAt(index);
curNum = (curNum * 10) + (ch - '0');
if (curNum <= 255) {
sb.append((char) ch);
restore(list, sb, s, index + 1, word, curNum);
sb.setLength(sb.length() - 1);
}
}
}
No comments:
Post a Comment