[Leetcode]46. Restore IP addresses restore IP address

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.