Algorithms—93.Restore IP Addresses

原创 2015年07月10日 19:05:34

思路:IP地址限制3位,取3个断点,保证前3位每位在1-3位,然后进行验证,通过验证的存进来。

 

耗时:288ms,中上游。

public class Solution {
    public List<String> restoreIpAddresses(String s) {
    	List<String> answerList=new ArrayList<String>();
        for (int i = 1; i <=3; i++) {
			for (int j = 1; j <=3; j++) {
				for (int k = 1; k <=3; k++) {
					int[] a={i,j,k};
					if (i+j+k<s.length()) {
						String t=new Solution().validate(s, a);
						if (!(t.equals(""))) {
							answerList.add(t);
						}
					}
				}
			}
		}
    	return answerList;
    }
    public String validate(String s,int[] a){
    	String s4=s.substring(a[0]+a[1]+a[2],s.length());
    	if (s4.length()>3||(s4.length()>1&&s4.substring(0, 1).equals("0"))||Integer.parseInt(s4)>255) {
			return "";
		}
    	String s1=s.substring(0,a[0]);
    	String s2=s.substring(a[0],a[0]+a[1]);
    	String s3=s.substring(a[0]+a[1],a[0]+a[1]+a[2]);
    	if ((s3.length()>1&&s3.substring(0, 1).equals("0"))||(s2.length()>1&&s2.substring(0, 1).equals("0"))||(s1.length()>1&&s1.substring(0, 1).equals("0"))||Integer.parseInt(s3)>255||Integer.parseInt(s2)>255||Integer.parseInt(s1)>255) {
			return "";
		}
    	return s1+"."+s2+"."+s3+"."+s4;
    }
}


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

93. Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combina...

LeetCode 93. Restore IP Addresses

1. 题目描述 Given a string containing only digits, restore it by returning all possible valid IP addre...

LeetCode 93. Restore IP Addresses 解题报告

LeetCode 93. Restore IP Addresses 解题报告 题目描述 Given a string containing only digits, restore it by r...

Leetcode 93. Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combina...

leetcode-93 Restore IP Addresses

原题链接: http://oj.leetcode.com/problems/restore-ip-addresses/  这道题的解法非常接近于NP问题,也是采用递归的解法。基本思路就是取出一个...

[JAVA]LeetCode93 Restore IP Addresses

[JAVA]LeetCode93 Restore IP Addresses

[leetcode] 93.Restore IP Addresses

题目: Given a string containing only digits, restore it by returning all possible valid IP address co...

Leetcode-93. Restore IP Addresses

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN...

【leetcode】String——Restore IP Addresses (93)

题目: Given a string containing only digits, restore it by returning all possible valid IP address ...

[Leetcode] 93. Restore IP Addresses 解题报告

题目: Given a string containing only digits, restore it by returning all possible valid IP addres...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)