zoukankan      html  css  js  c++  java
  • leetcode : Restore IP Addresses [回溯经典]???

    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 Solution {
        public List<String> restoreIpAddresses(String s) {
            List<String> result = new ArrayList<String>();
            if(s == null || s.length() < 4 || s.length() > 16) {
                return result;
            }
            
            helper(s, result, "", 0, 0);
            return result;
        }
        
        	public void helper(String s, List<String> res, String sb, int pos, int count) {
    		
    		if(pos >= s.length()) {
    			return;
    		}
    		
    		if(count == 3 && isValid(s.substring(pos, s.length()))) {
    			res.add(sb + s.substring(pos, s.length()));
    		}
    		
    		for(int i = pos; i<= pos + 3 && i<s.length(); i++) {
    			String str = s.substring(pos, i + 1);
    			if(isValid(str)) {
    				helper(s, res, sb + str + ".",i + 1, count + 1);
    			}
    		}	
    	}
    	
    	public boolean isValid(String str) {
    	if(str==null || str.length()>3)  
            return false;  
        int num = Integer.parseInt(str);  
        if(str.charAt(0)=='0' && str.length()>1)  
            return false;  
        if(num>=0 && num<=255)  
            return true;  
        return false;  
    	}
    }
    

      

  • 相关阅读:
    krakend 扩展开发概述
    varnish/api-gateway-benchmarks api gateway 性能压测工具
    krakend 加速配置工具
    krakend 支持发布订阅后端
    krakend 消费amqp mq 消息
    krakend cache 后端请求
    krakend 请求流量镜像的处理
    krakend 请求&&相应的检查
    krakend 的静态proxy
    krakend 的串行proxy
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6562411.html
Copyright © 2011-2022 走看看