Restore IP Addresses leetcode

lpy1990

Restore IP Addresses

Given a string containing only digits, restore it by returning all
possible valid IP address combinations.

For example: Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

回溯法

思路

for循环每一层从一个字符开始取到3个字符,再加一个isValid的函数来验证取的字符是否是合法数字,如果是合法的数字,我们再进行下一层递归,否则跳过。
return条件: 当取满三个数组, 并且剩下的第四个数组是合法的就return

复杂度

O(n^3)??

代码

public List<String> restoreIpAddresses(String s) {
    List<String> res = new ArrayList<String>();
    if (s == null || s.length() == 0) {
        return res;
    }
    if (s.length() < 4 || s.length() > 12){
        return res;
    }
    String sb = "";
    helper(s, res, sb, 0, 0);
    return res;
}
public void helper(String s, List<String> res, String sb, int pos, int count) {
    if (pos >= s.length()) {
        return;
    }
    if (count == 3 && isValid(s.substring(pos, s.length()))) {
        res.add(sb + s.substring(pos, s.length()));
        return;
    }
    for (int i = pos; i <= pos + 3 && i < s.length(); i++) {
        String str = s.substring(pos, i + 1);
        if (isValid(str)) {
            helper(s, res, sb + str + ".", i + 1, count + 1);
        }
    }
}
public boolean isValid(String s) {
    if (s.charAt(0) == '0') {
        return s.equals("0");
    }
    int p = Integer.parseInt(s);
    return p > 0 && p <= 255;
}
阅读 2k

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏