2/21/2013

Restore IP Addresses

Restore IP AddressesAug 8 '12
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)
This one is actually more tricky than it seems to be as it involves several corner cases.
DFS

  1. class Solution {
  2. public:
  3. vector<string> restoreIpAddresses(string s) {
  4. // Start typing your C/C++ solution below
  5. // DO NOT write int main() function
  6. if (s.size() > 12 || s.size() < 4) return vector<string>();
  7. return getValidIP(s.c_str(), 0);
  8. }
  9. vector<string> getValidIP(const char *c, int n) {
  10. const char *head = c;
  11. if (n == 3) {
  12. int num = 0;
  13. while (*c != '\0') {
  14. num = num * 10 + *c - '0';
  15. ++c;
  16. }
  17. vector<string> ret;
  18. // last segment requirements
  19. // at least one digit and at most one leading zero
  20. if (c - head > 1 && *head == '0' || c == head) return ret;
  21. // segment number cannot exceed 255
  22. if (num <= 255) {
  23. string seg(head, c - head);
  24. ret.push_back(seg);
  25. }
  26. return ret;
  27. }
  28. int num = 0;
  29. vector<string> ret;
  30. for (int i = 0; i < 3; ++i) {
  31. // reaches end or digits exceed 3
  32. if (*c == '\0' || c - head > 2) break;
  33. num = num * 10 + *c - '0';
  34. // each segment can be at most 255
  35. if (num > 255) break;
  36. vector<string> rest = getValidIP(++c, n + 1);
  37. string add_seg(head, c - head);
  38. for (auto s : rest) {
  39. string address(add_seg);
  40. address += ".";
  41. address += s;
  42. ret.push_back(address);
  43. }
  44. // only one leading 0 allowed
  45. if (*(c - 1) == '0' && i == 0) break;
  46. }
  47. return ret;
  48. }
  49. };

No comments:

Post a Comment