LeetCode93. 复原 IP 地址

思路

这个和切割回文串很类似,就是在切割后要判断下是否是ip地址。

这个的判断字符串是否是在0~255用的是ASCII码判断的,值得借鉴。

代码

class Solution {
    List res = new ArrayList<>();
    public List restoreIpAddresses(String s) {
        backtracking(s,0,0);
        return res;
    }
    public void backtracking(String s,int startIndex,int pointnum){
        if(pointnum == 3){
            if(isValid(s,startIndex,s.length()-1)){
                res.add(s);
                return;
            }
        }
        for(int i= startIndex;i end) {
            return false;
        }
        if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
            return false;
        }
        int num = 0;
        for (int i = start; i <= end; i++) {
            if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮数字字符不合法
                return false;
            }
            num = num * 10 + (s.charAt(i) - '0');
            if (num > 255) { // 如果⼤于255了不合法
                return false;
            }
        }
        return true;
        
    }
}

你可能感兴趣的:(LeetCode,leetcode,回溯)