码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 093 Restore IP Addresses

时间:2015-05-20 23:46:09      阅读:157      评论: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)

解题思路:

使用循环即可解决,JAVA实现如下:

	static public List<String> restoreIpAddresses(String s) {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 3; i++)
			for (int j = i + 2; j < i + 5&&j<=s.length()-2; j++)
				for (int k = j + 1; k < j + 4&&k<=s.length()-1; k++){
						if (isValid(s.substring(0, i + 1))
								&& isValid(s.substring(i + 1, j))
								&& isValid(s.substring(j, k))
								&& isValid(s.substring(k, s.length())))
							list.add(s.substring(0, i + 1) + "."
									+ s.substring(i + 1, j) + "."
									+ s.substring(j, k) + "."
									+ s.substring(k, s.length()));
					}
		return list;
	}
		public static boolean isValid(String s) {
		if (s.length()>3)
			return false;
		int num = Integer.parseInt(s);
		return num <= 255 && (num + "").equals(s);
	}

 

Java for LeetCode 093 Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4518358.html

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