zoukankan      html  css  js  c++  java
  • LeetCode 93. 复原IP地址

    https://leetcode-cn.com/problems/restore-ip-addresses/

    这个题很典型的回溯算法,但是要考虑的问题真的太多了,写的我好烦。

     public List<String> restoreIpAddresses(String s) {
            List<String> res = new ArrayList<>();
            if(s == null || s.length() == 0){
                return res;
            }
            backTracking(res,s,0,new ArrayList<>());
            return res;
        }
    
        public void backTracking(List<String> res, String str, int index, List<String> list){
            //如果list中已经有4个元素,就进入判断,但是要成为一个真正的答案还需要它已经遍历到了字符串的结尾。
            if(list.size() == 4){
                if(index == str.length()){
                    res.add(String.join(".",list));
                }
                return;
            }
    
            for(int j = 1; j < 4 ; j++){
                //防止数组越界
                if(j + index > str.length()){
                    break;
                }
                String temp = str.substring(index,index+j);
                //判断0开头的IP,以及是大于255的IP
                if((temp.startsWith("0") && temp.length() > 1) || ((Integer.parseInt(temp) > 255) && temp.length() == 3)){
                    continue;
                }
                list.add(temp);
                backTracking(res,str,index+j,list);
                list.remove(list.size()-1);
            }
        }
  • 相关阅读:
    四种wordpress常用的循环结构
    自动创建网页文章目录结构
    shell
    SSH
    架构
    Https
    if-else、switch、while、for
    do-while
    const
    Tail Call
  • 原文地址:https://www.cnblogs.com/ZJPaang/p/13040591.html
Copyright © 2011-2022 走看看