Given a string containing only digits, restore it is returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
Return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
Idea: the subject with recursive implementation, an IP address only 3 points, according to the number of points to judge the legal non-law (also is that the string length can only be more than the number of points, and less than k+1), K is the number of points.
If you do not need to add a point at the end, the field value is less than 256, then it is legal to add a result set.
The code is as follows:
public class Solution {list<string> List; Public list<string> restoreipaddresses (String s) {List = new arraylist<string> (); /** * The initial incoming string length can only be 4-12 */Adddot (S, "", 3); return list; }/** * * @param s string to be processed * @param result loading String * @param k there are currently several "." */private void Adddot (string s,string result, int k) {//incoming string must be valid if (S.length () <= k) {return; } if (S.length () > K+1) {return; } if (k = = 0) {//Last paragraph, judging less than (S.charat (0) = = ' 0 ' && s.length () > 1) | | Integer.parseint (s) >=) return; List.add (Result + "." + s); Return }//Traverse the front 3 bits, if less than 256, then participate in recursion for (int i = 1; I <= s.length (); i++) {String temp = s.substring (0,i);//The current segment is less than 256, which means it is legal, can continue if (Integer.parseint (temp) <) {String str = s.substring (i); If result is null, the preceding "." is not added. if (result.length () > 0) {temp = result + "." + temp; } Adddot (Str,temP, k-1); If the first number is 0, the loop will no longer continue if (S.charat (0) = = ' 0 ') {break; }}else{break; } } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 93.Restore IP Addresses (restore IP Address) Thinking and method of solving problems