93. Restore IP Addresses -Medium

来源:互联网 发布:圣人不出门知天下事 编辑:程序博客网 时间:2024/06/06 08:45

Question

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

给出一个仅包含数字的字符串,返回所有可靠的IP的组合

Example

Given “25525511135”,

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

Solution

  • 回溯解。每次判断以当前字符开头的字符串是否属于可靠的子字符串,如果可靠则继续判断后面的,否则跳过。仅当字符串刚好划分为可靠的4个子字符串([0:255])时保存当前组合。在判断每个子字符串时,主要确保 0 <= int(s) <=255,且排除 “01”等情况的子字符串

    public class Solution {    public List<String> restoreIpAddresses(String s) {        List<String> res = new ArrayList<>();        backtracking(s, 0, res, "", 0);        return res;    }    /**     * 思路:每次判断以开始索引的字符开头的字符串是否属于可靠的子字符串,如果可靠则继续判断后面的,否则跳过     *       仅当字符串刚好划分为可靠的4块([0:255])保存结果     * @param s:需要分割的字符     * @param start:开始索引     * @param res:保存结果     * @param temp:保存当前组合     * @param count:当前分割的子字符串个数     */    public void backtracking(String s, int start, List<String> res, String temp, int count){        // 如果子字符串个数大于4个或者已经取完了所有字符串的元素,则返回        if(count > 4 || start > s.length()) return;        // 如果分为4个子字符串时刚好分割完原字符串,则添加到结果集        if(count == 4 && start == s.length()) res.add(temp);        // 判断以s[start]开始的字符串是否可靠,如果可靠则继续判断后面的,否则跳过        // 因为字符串的大小不能大于255,所以位数不可能大于3位数        for(int i = start; i < start + 3; i++){            // 保证当前i索引没有超出字符串范围            if(i < s.length()) {                String substr = s.substring(start, i + 1);                // 如果一个字符串的第一位为0且位数大于1(如01)或者大于255则跳过                if ((substr.startsWith("0") && substr.length() > 1) || Integer.parseInt(substr) > 255) continue;                //回溯,每当已经分割出3个子字符串,第4个字符串后面不加 "."                backtracking(s, i + 1, res, temp + substr + (count == 3 ? "" : "."), count + 1);            }        }    }}
0 0