public class Solution {
/**
* @param s the IP string
* @return All possible valid IP addresses
*/
public ArrayList<String> restoreIpAddresses(String s) {
// Write your code here
ArrayList<String> result = new ArrayList<String>();
if (s == null || s.length() < 4 || s.length() > 12) {
return result;
}
helper(s, 0, "", result, 0);
return result;
}
private void helper(String s, int start, String tmp, ArrayList<String> result, int points) {
if (start == s.length() && points == 4) {
result.add(tmp);
return;
}
for (int i = 1; i <= 3 && start + i <= s.length(); i++) {
if (Integer.parseInt(s.substring(start, start + i)) <= 255) {
String tail = s.substring(start, start + i);
if (!tail.equals(Integer.toString(Integer.parseInt(tail)))) {
return;
}
if (points != 3) tail += ".";
helper(s, start + i, tmp + tail, result, points + 1);
}
}
}
}
好久不练,一个dfs写了半小时也是太差T_T
没有评论:
发表评论