1. 程式人生 > >LeetCode 93 Restore IP Addresses

LeetCode 93 Restore IP Addresses

ip 回溯

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)

給一個字符串,轉成可能組成的IP數

public class Solution 
{
    //深度優先遍歷,DFS即可實現
    List<String> res=new ArrayList<String>();
    public List<String> restoreIpAddresses(String s) 
    {
        //特殊情況處理
        if(s==null || s.length()<=0 || s.length()<4 || s.length()>12)
            return res;

        String one="";
        byDFS(s,0,0,one);
        return res;
    }

    //index 記錄開始的位置,k記錄截取的數量,
    void byDFS(String s, int index,int k,String one) 
    {
        if(k==3)
        {
            String tmp = s.substring(index, s.length());
            if(check(tmp))
                res.add(one+tmp);
            return ;
        }else
        {
            //每一次最長的截取長度是i,最短1位,最長3位
            for(int i=1;i<=3 && index+i < s.length() ;i++)
            {
                String tmp = s.substring(index, index+i);
                if(check(tmp))
                    byDFS(s, index+i, k+1, one+tmp+".");
            }
        }
    }

    public boolean check(String ip) 
    {
        //以0開始的字符串,只有0是合理的,其余的比如001等等都不是合理的
        if(ip.charAt(0)==‘0‘)
        {
            if(ip.equals("0"))
                return true;
            else
                return false;
        }else
        {
            int ipNum=Integer.parseInt(ip);
            if(ipNum>0 && ipNum<=255)
                return true;
            else
                return false;
        }
    }
}

哎,映客線下筆試題。好難哦。雖然想到是回溯,但是沒做出來,沒想到是LT原題。gg。

LeetCode 93 Restore IP Addresses