📜  从给定字符串生成所有可能的有效IP地址的程序|套装2

📅  最后修改于: 2021-04-24 21:58:30             🧑  作者: Mango

给定仅包含数字的字符串,请通过返回所有可能的有效IP地址组合来恢复它。
有效的IP地址必须采用ABCD的形式,其中ABCD0到255之间的数字。除非它们是0,否则它们不能以0为前缀。

例子:

方法:可以使用回溯解决此问题。在每个呼叫中,我们都有三个选项来创建一个有效IP地址的单个数字块:

  1. 仅选择一个数字,添加一个点,然后移至选择其他块(其他函数调用)。
  2. 或同时选择两个数字,添加一个点并进一步移动。
  3. 或选择三个连续的数字并移动到下一个块。

在第四个块的末尾,如果所有数字都已使用并且生成的地址是有效的ip地址,则将其添加到结果中,然后通过删除在上一个调用中选择的数字进行回溯。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
#include 
using namespace std;
  
// Function to get all the valid ip-addresses
void GetAllValidIpAddress(vector& result,
                          string givenString, int index,
                          int count, string ipAddress)
{
  
    // If index greater than givenString size
    // and we have four block
    if (givenString.size() == index && count == 4) {
  
        // Remove the last dot
        ipAddress.pop_back();
  
        // Add ip-address to the results
        result.push_back(ipAddress);
        return;
    }
  
    // To add one index to ip-address
    if (givenString.size() < index + 1)
        return;
  
    // Select one digit and call the
    // same function for other blocks
    ipAddress = ipAddress
                + givenString.substr(index, 1) + '.';
    GetAllValidIpAddress(result, givenString, index + 1,
                         count + 1, ipAddress);
  
    // Backtrack to generate another poosible ip address
    // So we remove two index (one for the digit
    // and other for the dot) from the end
    ipAddress.erase(ipAddress.end() - 2, ipAddress.end());
  
    // Select two consecutive digits and call
    // the same function for other blocks
    if (givenString.size() < index + 2
        || givenString[index] == '0')
        return;
    ipAddress = ipAddress + givenString.substr(index, 2) + '.';
    GetAllValidIpAddress(result, givenString, index + 2,
                         count + 1, ipAddress);
  
    // Backtrack to generate another poosible ip address
    // So we remove three index from the end
    ipAddress.erase(ipAddress.end() - 3, ipAddress.end());
  
    // Select three consecutive digits and call
    // the same function for other blocks
    if (givenString.size() < index + 3
        || stoi(givenString.substr(index, 3)) > 255)
        return;
    ipAddress += givenString.substr(index, 3) + '.';
    GetAllValidIpAddress(result, givenString, index + 3,
                         count + 1, ipAddress);
  
    // Backtrack to generate another poosible ip address
    // So we remove four index from the end
    ipAddress.erase(ipAddress.end() - 4, ipAddress.end());
}
  
// Driver code
int main()
{
    string givenString = "25525511135";
  
    // Fill result vector with all valid ip-addresses
    vector result;
    GetAllValidIpAddress(result, givenString, 0, 0, "");
  
    // Print all the generated ip-addresses
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << "\n";
    }
}


Python3
# Python3 implementation of the approach 
  
# Function to get all the valid ip-addresses 
def GetAllValidIpAddress(result, givenString,
                         index, count, ipAddress) :
  
    # If index greater than givenString size 
    # and we have four block 
    if (len(givenString) == index and count == 4) :
  
        # Remove the last dot 
        ipAddress.pop(); 
  
        # Add ip-address to the results 
        result.append(ipAddress); 
        return; 
  
    # To add one index to ip-address 
    if (len(givenString) < index + 1) :
        return; 
  
    # Select one digit and call the 
    # same function for other blocks 
    ipAddress = (ipAddress + 
                 givenString[index : index + 1] + ['.']); 
      
    GetAllValidIpAddress(result, givenString, index + 1,
                                 count + 1, ipAddress); 
  
    # Backtrack to generate another poosible ip address 
    # So we remove two index (one for the digit 
    # and other for the dot) from the end 
    ipAddress = ipAddress[:-2];
  
    # Select two consecutive digits and call 
    # the same function for other blocks 
    if (len(givenString) < index + 2 or 
            givenString[index] == '0') :
        return; 
          
    ipAddress = ipAddress + givenString[index:index + 2] + ['.']; 
    GetAllValidIpAddress(result, givenString, index + 2, 
                                  count + 1, ipAddress); 
  
    # Backtrack to generate another poosible ip address 
    # So we remove three index from the end 
    ipAddress = ipAddress[:-3]; 
  
    # Select three consecutive digits and call 
    # the same function for other blocks 
    if (len(givenString)< index + 3 or 
        int("".join(givenString[index:index + 3])) > 255) :
        return; 
    ipAddress += givenString[index:index + 3] + ['.']; 
    GetAllValidIpAddress(result, givenString, 
                         index + 3, count + 1, ipAddress); 
  
    # Backtrack to generate another poosible ip address 
    # So we remove four index from the end 
    ipAddress = ipAddress[:-4]; 
  
# Driver code 
if __name__ == "__main__" : 
    givenString = list("25525511135"); 
  
    # Fill result vector with all valid ip-addresses 
    result = [] ; 
    GetAllValidIpAddress(result, givenString, 0, 0, []); 
  
    # Print all the generated ip-addresses 
    for i in range(len(result)) :
        print("".join(result[i])); 
          
# This code is contributed by Ankitrai01


输出:
255.255.11.135
255.255.111.35