原题地址:https://leetcode-cn.com/problems/restore-ip-addresses/submissions/
题目描述:
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
解题方案:
这道题在刚开始解的时候忘记在一层遍历完之后要去掉点,意识到之后又思考了很久如何去掉点。没有意识到的问题还有最后剩下的数字可能不足3个,以及类似“00”,“010”这种情况不合理。在网上看到说到最后一层时直接计算剩余所有数字,这种想法比我做的要简单得多了,不过实验了一下发现时间复杂度没有改善。这道题总体来说做的质量比较低,想得过于复杂,没有想到比较直接的方法。这也是我经常会遇到的一个问题...
代码:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
string temp;
vector<string> result;
getAns(temp, s, 0, result, 0);
return result;
}
void getAns(string temp, string s, int pos, vector<string>& result, int time)
{
if(pos >= s.length() && time == 4)
{
result.push_back(temp);
}
else
{
int m = s.length() - pos;
m = m > 3 ? 3 : m;
for(int i = 1; i <= m; i ++)
{
if(time >= 4)
{
return;
}
string s1 = s.substr(pos, i);
if(s1[0] == '0' && s1.length() > 1)
continue;
stringstream ss;
int num;
ss << s1;
ss >> num;
if(num < 0 || num > 255)
continue;
temp.append(s1);
if(time < 3)
temp.append(".");
time ++;
pos += i;
getAns(temp, s, pos, result, time);
pos -= i;
time --;
if(time < 3)
temp = temp.substr(0, temp.length() - i - 1);
else
temp = temp.substr(0, temp.length() - i);
}
}
}
};