Thought: Easy to think of dfs. Then try to code it.
Code:
public class Solution {
public static ArrayList<String> result;
public static StringBuilder cache;
public ArrayList<String> restoreIpAddresses(String s) {
result = new ArrayList<String>();
cache = new StringBuilder();
if (s.length() <= 3) return result;
dfs(s, 0, 4, 0);
return result;
}
public boolean isValid(String s) {
if (s.length() == 1) return true;
else if (s.length() == 2) {
return s.charAt(0) != '0';
}else if (s.length() == 3) {
if (s.charAt(0) == '0') return false;
if (s.charAt(0) == '1') return true;
if (s.charAt(0) >= '3') return false;
else {
if (s.charAt(1) <= '4') return true;
if (s.charAt(1) >= '6') return false;
else {
return s.charAt(2) <= '5';
}
}
}else {
return false;
}
}
public void dfs(String s, int segment, int target, int current) {
if (segment == target) {
if (current == s.length()) {
cache.delete(cache.length() - 1, cache.length());
result.add(cache.toString());
cache.append('.');
return;
}else {
return;
}
}
if (current < s.length() && isValid(s.substring(current, current + 1))) {
cache.append(s.substring(current, current + 1));
cache.append('.');
dfs(s, segment + 1, target, current + 1);
cache.delete(cache.length() - 2, cache.length());
}
if ((current < s.length() - 1) && isValid(s.substring(current, current + 2))) {
cache.append(s.substring(current, current + 2));
cache.append('.');
dfs(s, segment + 1, target, current + 2);
cache.delete(cache.length() - 3, cache.length());
}
if ((current < s.length() - 2) && isValid(s.substring(current, current + 3))){
cache.append(s.substring(current, current + 3));
cache.append('.');
dfs(s, segment + 1, target, current + 3);
cache.delete(cache.length() - 4, cache.length());
}
}
}
No comments:
Post a Comment