题目:
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)
这道题目是考察我们对数的划分,将一串数划分为4个部分,每一部分的范围相同,都为0到255,文共有多少个划分,这道题目我没想到有特别好的做法,只是采取了一般的方法,用三个变量i,j,k把其分为4个部分,每一部分分别对其进行合理性检查,若每一部分都合理的话,则视为一个可行的划分。遍历整个字符串,看共有多少个划分即可。
一种c++的实现方式如下:
#include<iostream> #include<vector> #include<string> #include<cstdlib> using namespace std; class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> res; int num = s.length(); string plot = "."; for(int i = 1; i < 4 && i < num-2; i++) { for(int j = i+1; j < i+4 && j < num-1; j++) { for(int k = j+1; k < j+4 && k < num; k++) { string s0 = substring(0,i-1,s); string s1 = substring(i,j-1,s); string s2 = substring(j,k-1,s); string s3 = substring(k,num-1,s); if(validString(s0) && validString(s1) && validString(s2) && validString(s3) ) { string temp; temp += s0+plot+s1+plot+s2+plot+s3; res.push_back(temp); } } } } return res; } string substring(int start, int end, string s) { string temp; int num = end - start+1; for(int i = 0; i < num; i++) { temp += s[start+i]; } return temp; } bool validString(string s) { if(s.length() > 3 || s.length() == 0 || (s.length()>1 && s[0]=='0') || atoi(s.c_str())>255 ) { return false; } else { return true; } } };