码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Restore IP Addresses

时间:2015-04-21 16:06:05      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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个数。

思路:dfs处理,最多就4层递归,因为ip最多就是由4个数组成的。

public class Solution {
   public List<String> restoreIpAddresses(String s) {
    	List<String> result = new ArrayList<String>();
    	if (s.length() < 4 || s.length() > 15) return result;
    	
    	List<String> tmp = new ArrayList<String>();
    	dfs(result, tmp, 0, 0, s);
    	return result;
    }
    
    private void dfs(List<String> result, List<String> tmp, int dep, int cur, String s) {
		if (dep >= 4) {
			if (cur == s.length()) {
				StringBuilder ans = new StringBuilder();
				ans.append(tmp.get(0));
				for (int i = 1; i < 4; i++)
					ans.append("." + tmp.get(i));
				result.add(ans.toString());
			}
			return;
		}
		
		for (int k = 1; k <= 3 && cur+(k-1) < s.length(); k++) {
			String num = s.substring(cur, cur+k);
			if (isValid(num)) {
				tmp.add(num);
				dfs(result, tmp, dep+1, cur+k, s);
				tmp.remove(tmp.size()-1);
			}
		}
	}

	private boolean isValid(String num) {
		if (num.length() == 1 && num.compareTo("0") >= 0 && num.compareTo("9") <= 0) return true;
		if (num.length() == 2 && num.compareTo("10") >= 0 && num.compareTo("99") <= 0) return true;
		if (num.length() == 3 && num.compareTo("100") >= 0 && num.compareTo("255") <= 0) return true;
		return false;
	}
}



LeetCode Restore IP Addresses

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45171215

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!