LeetCode 93 Restore IP Addresses

来源:互联网 发布:大淘客cms要多久能过 编辑:程序博客网 时间:2024/06/05 16:06

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)

思路:暴力破解,不过需要注意以下几点:

1.输入的长度必须是4~12之间的数(可以包括4、12)。

2.每个点前面数字不能是0*或者0**,每个数字必须是0~255之间的数。

public class Solution {public List<String> restoreIpAddresses(String s) {ArrayList<String> result = new ArrayList<String>();if (s.length() < 4 || s == null || s.length() > 12) return result;int i, j, k;String temp1, temp2, temp3, temp4;StringBuffer sb;for (i = 1; i < 4; i++) {while (s.length() - i > 9) i++;temp1 = s.substring(0, i);for (j = 1; j < 4 && (i + j) < s.length(); j++) {while (s.length() - i - j > 6) j++;temp2 = s.substring(i, i + j);for (k = 1; k < 4 && (i + j + k) < s.length(); k++) {while (s.length() - i - j - k > 3) k++;temp3 = s.substring(i + j, i + j + k);temp4 = s.substring(i + j + k, s.length());if (Integer.parseInt(temp1) < 256&& Integer.parseInt(temp2) < 256&& Integer.parseInt(temp3) < 256&& Integer.parseInt(temp4) < 256&& !temp1.matches("0\\d+")&& !temp2.matches("0\\d+")&& !temp3.matches("0\\d+")&& !temp4.matches("0\\d+")) {sb = new StringBuffer(s);sb.insert(i + j + k, '.');sb.insert(i + j, '.');sb.insert(i, '.');result.add(sb.toString());}}}}return result;}

0 0
原创粉丝点击