My accepted java solution


  • 0
    S

    public List<String> restoreIpAddresses(String s)

    {
    
            List<String> lstOfIpAddr=new ArrayList<String>();
            if(s==null || s.trim().length()<4 || s.trim().length()>12) return lstOfIpAddr; 
            String ip[]=new String[4];
            for(int i=3;i>0;i--) {
                String soFar=s.substring(0,i);
                String remaining=s.substring(i,s.length());
                if(i==1 || (soFar.charAt(0)!='0' && Integer.parseInt(soFar)<=255)){
                    ip[0]=soFar;
                     getIPAddress(remaining,ip,0,lstOfIpAddr);
                }
            }
            return lstOfIpAddr;
        }
        public void getIPAddress(String reamining,String[] ip,int counter,List<String> lstOfIpAddr){
                if((reamining==null || reamining.length()==0) && counter==3){
                	lstOfIpAddr.add(ip[0]+"."+ip[1]+"."+ip[2]+"."+ip[3]);
                	return;
                } else if((reamining==null || reamining.length()==0) && counter<3) {
                   return; 
                } else if(reamining.length()>0 && counter>=3) {
                   return; 
                }
                int start=reamining.length()<3?reamining.length():3;
                for(int i=start;i>0;i--) {
                    String soFar1=reamining.substring(0,i);
                    String remaining1=reamining.substring(i,reamining.length());
                    if(i==1 || (soFar1.charAt(0)!='0' && Integer.parseInt(soFar1)<=255)){
                        ip[counter+1]=soFar1;
                        getIPAddress(remaining1,ip,counter+1,lstOfIpAddr);
                        
                    }
                }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.