题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解题思路:递归+回溯
IP地址一共有四个整数组成,每次递归找出一个有效的整数,当选择4个整数,并且字符串s也已经达到末尾,即找到一个有效的IP地址。
如果s的长度小于4或者大于12,一定不能组合成一个有效的IP,直接返回空列表
AC代码:
- class Solution {
- public List
result; - public List
tem; - public List
restoreIpAddresses(String s) { - result = new ArrayList<>();
- tem = new ArrayList<>();
- if (s.length() < 4 || s.length() > 12) {
- return result;
- }
- process(s, 0);
- return result;
- }
-
- public void process(String s, int index) {
- if (index >= s.length() && tem.size() == 4) {
- StringBuilder ans = new StringBuilder();
- for (int i = 0; i < tem.size(); i++) {
- if (i==0){
- ans.append(tem.get(i));
- }else {
- ans.append(".").append(tem.get(i));
- }
- }
- result.add(ans.toString());
- return;
- } else if (index >= s.length()||tem.size()==4) {
- return;
- }
-
- for (int i = 1; i <= 3; i++) {
- if (index + i > s.length()) {
- break;
- }
- String part = s.substring(index, index + i);
- if (s.charAt(index) == '0') {
- tem.add("0");
- process(s, index + 1);
- tem.remove(tem.size() - 1);
- break;
- } else if (part.length() <= 2 || part.compareTo("255") <= 0) {
- tem.add(part);
- process(s, index + i);
- tem.remove(tem.size() - 1);
- }
- }
- }
- }
