LeetCode-93. Restore IP Addresses (JAVA)(重新组合IP)

93. 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)

backtracking, 找出第一部分合法的IP, 剩余部分变成相似子问题。

	public List restoreIpAddresses(String s) {
		List res = new ArrayList();
		if (s.length() < 4 || s.length() > 12)
			return res;
		dfs(s, "", res, 1);
		return res;
	}

	public void dfs(String s, String temp, List res, int count) {
		if (count == 4 && isValid(s)) {
			res.add(temp + s);
			return;
		}
		// Math.min(4, s.length())后面几位少于4的情况比如,0000
		for (int i = 1; i < Math.min(4, s.length()); i++) {
			String cur = s.substring(0, i);
			if (isValid(cur)) {
				// i 是beginIndex
				dfs(s.substring(i), temp + cur + ".", 
						res, count + 1);
			}
		}
	}

	public boolean isValid(String s) {
		// 前导0,如果第一个字符是0,只能一个为0
		if (s.charAt(0) == '0')
			return s.equals("0");
		int num = Integer.parseInt(s);
		return 0 < num && num < 256;
	}

discuss:回溯

	public List restoreIpAddresses(String s) {
		List res = new ArrayList<>();
		helper(s, "", res, 0);
		return res;
	}

	public void helper(String s, String tmp, 
			List res, int n) {
		// 剪枝,因ip不会超过三位
		if (s.length() > 3 * (4 - n))
			return;
		if (n == 4) {
			if (s.length() == 0)
				// substring here to get rid of last '.'
				// 去掉最后一个'.'
				res.add(tmp.substring(0, tmp.length() - 1));
			return;
		}
		for (int k = 1; k <= 3; k++) {
			// 如果剩余的长度还不够k那么说明不能排列成ip
			if (s.length() < k)
				break;
			int val = Integer.parseInt(s.substring(0, k));
			// in the case 010 the parseInt will return len=2
			// where val=10, but k=3, skip this.
			// k != String.valueOf(val).length(),为了避免前导0情况
			if (val > 255 || k != String.valueOf(val).length())
				continue;

			helper(s.substring(k), tmp + s.substring(0, k)
			+ ".", res, n + 1);
		}
	}
直接使用循环:

public List restoreIpAddresses(String s) {
		List res = new ArrayList();
		int len = s.length();
		for (int i = 1; i < 4 && i < len - 2; i++) {
			for (int j = i + 1; j < i + 4 && j < len - 1; j++) {
				for (int k = j + 1; k < j + 4 && k < len; k++) {
					String s1 = s.substring(0, i), 
							s2 = s.substring(i, j), 
							s3 = s.substring(j, k),
							s4 = s.substring(k, len);
					if (isValid(s1) && isValid(s2)
							&& isValid(s3) && isValid(s4)) {
						res.add(s1 + "." + s2 + "." 
							+ s3 + "." + s4);
					}
				}
			}
		}
		return res;
	}

	public boolean isValid(String s) {
		if (s.length() > 3 || s.length() == 0 
				|| (s.charAt(0) == '0' && s.length() > 1) 
				|| Integer.parseInt(s) > 255)
			return false;
		return true;
	}


你可能感兴趣的:(leetcode)