Clear java solution


  • 0
    L
    public List<String> restoreIpAddresses(String s) {
            List<String> res = new ArrayList<>();
            if(s==null||s.length()<4||s.length()>12)
            	return res;
            dfsIP(res, s, "", 0, 0);
            return res;
        }
        
        public void dfsIP(List<String> res, String s, String ele, int piv, int pos){
    		if(pos==4&&s.length()==piv){
    			res.add(ele.substring(0, ele.length()-1));
    			return;
    		}
    		for(int i=1;i<4&&piv+i<=s.length();i++){
    			String part = s.substring(piv, piv+i);
    			if(ipValid(part)){
    				ele+=part+".";
    				dfsIP(res, s, ele, piv+i, pos+1);
    				ele = ele.substring(0, ele.length()-i-1);
    			}
    		}
    		
    	}
    	
    	public Boolean ipValid(String ip){
    		if(ip.charAt(0)=='0')
    			return ip.equals("0");
    		int v = Integer.parseInt(ip);
    		if(v>0&&v<=255)
    			return true;
    		return false;
    	}
    

Log in to reply
 

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