leetcode 93. Restore IP Addresses

来源:互联网 发布:影子网络怎么进入 编辑:程序博客网 时间:2024/04/30 10:14

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)

Subscribe to see which companies asked this question.

public class Solution {    public List<String> restoreIpAddresses(String s) {        List<String> list = new LinkedList<>();        if (s.length() < 4||s.length()>16) return list;        int a1 = 0;        int a2 = 0;        int a3 = 0;        int a4 = 0;        for (int q1 = 1; q1 < 4; q1++) {            a1 = Integer.valueOf(s.substring(0, q1));            if (a1 > 255 || s.length() - q1 + 1 < 3) {                break;            }            for (int q2 = 1; q2 < 4; q2++) {                a2 = Integer.valueOf(s.substring(q1, q1 + q2));                if (a2 > 255 || s.length() - q1 + 1 - q2 + 1 < 2||q1 + q2 >=s.length()) {                    break;                }                for (int q3 = 1; q3 < 4; q3++) {                    a3 = Integer.valueOf(s.substring(q1 + q2, q1 + q2 + q3));                    if (a3 > 255 || s.length() - q1 + 1 - q2 + 1 + q3 + 1 < 1||q1 + q2 + q3>=s.length()) {                        break;                    }                    if(s.length()-s.substring(0, q1 + q2 + q3).length()>4){                        continue;                    }                    a4 = Integer.valueOf(s.substring(q1 + q2 + q3, s.length()));                    if (a4 > 255) {                        continue;                    }                    String str = a1 + "." + a2 + "." + a3 + "." + a4 + "";                    if(str.length()==s.length()+3){                        list.add(str);                    }                }            }        }        return list;    }}

0 0
原创粉丝点击