恢复IP地址

目的:掌握基本递归算法设计

内容:编写程序exp5-3.cpp,恢复IP地址。给定一个仅仅包含数字的字符串,恢复它的所有可能的有效IP地址。例如,给定字符串为“22522511135”,返回“225.225.11.135”和“225.225.111.35”(顺序可以任意)。

思路:首先要确定退出递归的条件有:

  • 扫描的迭代器大于字符串长度
  • 递归次数大于3
  • 截取的字符串的第一个字符为0并且后面还有字符
  • 截取的字符串数字大于255

然后判断是否要添加"."或者是递归次数等于3时把它放进result中,递归查找下一个可能出现的情况。

#include
#include
#include
#include
#include
#include
#include
#include
#include 
using namespace std;
string s;
set  result;
void getIP(string temp,int st,int en,int time)//获取IP地址
{
    if(en>s.size())
        return ;
    if(time>3)
        return ;
    string sub=s.substr(st,en-st);
    if(sub[0]=='0'&&sub.size()>1)
        return ;
    int num=atoi(sub.substr(0,en-st).c_str());
    if(num>255)
        return ;
    temp+=sub;
    if(en!=s.size())
        temp+=".";
    else
    {
        if(time==3)
            result.insert(temp);
            return ;
    }
    getIP(temp,en,en+1,time+1);
    getIP(temp,en,en+2,time+1);
    getIP(temp,en,en+3,time+1);
}
void printfIP()//输出结果
{
    if(result.empty())
    {
        printf("输入不合法\n");
    }
    else
    {
        set ::iterator a;
        printf("可能有效的IP地址有:\n");
        for(a=result.begin();a!=result.end();a++)
            cout<<*a<>s;
        string temp="";
        getIP(temp,0,1,0);
        getIP(temp,0,2,0);
        getIP(temp,0,3,0);
        printfIP();
        printf("继续请输入1,退出操作请输入0\n");
        cin>>num;
        if(num==0)
            break;
        else
            continue;
    }
    return 0;
}

你可能感兴趣的:(数据结构)