• leetcode — restore-ip-addresses


    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * Source : https://oj.leetcode.com/problems/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)
     */
    public class RestoreIpAddress {
    
        public void recursion (String str, int index, int count, String ipStr, List<String> result) {
            if (index == str.length()) {
                if (count == 4) {
                    result.add(ipStr.substring(0, ipStr.length()-1));
                }
                return;
            }
    
            // ip由四个数字组成
            if (count == 4) {
                return;
            }
    
            for (int i = index; i < str.length() && i < index + 3 ; i++) {
                // ip最大是255,如果是三位数第一位最大只能是2
                if (i - index > 1 && str.charAt(index) > '2') {
                    return;
                }
                ipStr += str.substring(index, i+1) + ".";
                recursion(str, i+1, ++count, ipStr, result);
                ipStr = ipStr.substring(0, ipStr.length() - (i - index + 2));
                count --;
            }
        }
    
        public List<String> restore (String str) {
            if (str.length() < 4) {
                return Collections.EMPTY_LIST;
            }
            List<String> result = new ArrayList<String>();
            String ipStr = "";
            recursion(str, 0, 0, ipStr, result);
            return result;
        }
    
    
        public static void main(String[] args) {
            RestoreIpAddress restoreIpAddress = new RestoreIpAddress();
            List<String> list = restoreIpAddress.restore("25525511135");
            System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
    
            list = restoreIpAddress.restore("11111");
            System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
    
            list = restoreIpAddress.restore("19813713411");
            System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
    
            list = restoreIpAddress.restore("");
            System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
        }
    }
    
  • 相关阅读:
    MyBatis Plus 导入IdType失败
    SpringBoot+Vue项目上手
    高并发
    多线程
    Java 接口
    Java后端总结
    Aliyun Linux2安装Docker
    Zookeeper集群部署及报错分析
    CentOs7配置java环境
    kafka笔记——kafka启动
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7788328.html
Copyright © 2020-2023  润新知