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)
Subscribe to see which companies asked this question
Solution 1: Brute force method. The three-layer loop determines the first three digits, the last remaining all as the fourth number. The actual cycle of each layer is performed up to three times. Use the conditions in the loop as the correct IP address to prune. Attention needs to be given to various boundary conditions.
classSolution { Public: Vector<string> restoreipaddresses (strings) {intn =s.size (); stringAddr =""; Vector<string>Res; for(inti =0; I < n-3&& I <3; ++i) {stringFir (S.begin (), s.begin () + i +1); if((fir[0] !='0'|| Fir.size () = =1) && Stoi (FIR) <=255) { for(intj = i +1; J < N-2&& J < i +4; ++j) {stringSEC (S.begin () + i +1, S.begin () + j +1); if((sec[0] !='0'|| Sec.size () = =1) && Stoi (sec) <=255) { for(intK = j +1; K < n-1&& K < J +4; ++k) {stringTRD (S.begin () + j +1, S.begin () + K +1); if((trd[0] !='0'|| Trd.size () = =1) && Stoi (TRD) <=255) { stringFth (S.begin () + K +1, S.end ()); if((fth[0] !='0'|| Fth.size () = =1) && Fth.size () <4&& Stoi (fth) <=255) {addr+ = Fir +'.'+ sec +'.'+ TRD +'.'+fth; Res.push_back (addr); Addr.clear (); } } } } } } } returnRes; }};
[Leetcode]46. Restore IP addresses restore IP address