• 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()])));
        }
    }
    
  • 相关阅读:
    使用springboot方式配置监听器
    Socket实现服务端
    Tesseract 部署到centos遇到的坑
    Java 机器学习之K-mean
    Java springboot之Mongodb增删改查
    Vue 跳转
    nginx安装、部署前端、请求转发
    Vue 第十四章 Vue项目部署到tomcat服务器
    Vue 第十三章 watch属性和computed属性使用
    Vue 第十二章 命名视图实现经典布局
  • 原文地址:https://www.cnblogs.com/sunshine-2015/p/7788328.html
Copyright © 2020-2023  润新知