ip地址还原(数据结构课本第五章实验三)

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

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

#include<iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
const int maxn=20;
typedef struct node
{
	char s[20];
	int len;
}qstring;
qstring *a,*b;
int my_atoi (char s[],int i,int j)
{
	int n;
	for(n=0;i<j;i++)
		n=10*n+(s[i]-'0');//将数字字符转换成整形数字
	return n;
}
void init(char* x,qstring *&a)//将 字符串 x 赋值给 qstring 类型的 a
{
	int i,xlen=strlen(x);
	memset(a->s,'0',sizeof a->s);
	memset(b->s,'0',sizeof b->s);
	a->len=xlen;
	for(i=0;i<xlen;i++)
		a->s[i]=x[i];
}
void digui(int i,int j)
{
	if(j<4){
		for(int k=1;k<=3;k++){
			if(i+k>a->len)
				continue;
			int num=my_atoi(a->s,i,i+k);
			if(num<=255&&i+k<a->len&&a->len-i-1>=4-j&&a->len-i-1-k<3*(4-j)){
				for(int h=0;h<k;h++)
					b->s[b->len++]=a->s[h+i];
				b->s[b->len++]='.';
				digui(i+k,j+1);
				b->len=b->len-k-1;
			}
		}
	}
	else if(j==4){
		int num=my_atoi(a->s,i,a->len);
		if(num<=255){
			for(int h=i;h<a->len;h++)
				b->s[b->len++]=a->s[h];
			if(b->len==a->len+3){
				for(int h=0;h<b->len;h++)
					cout<<b->s[h];
				cout<<endl;
			}
			b->len=i+3;
		}
	}
}
void solve(char *x)
{
	a=(qstring *)malloc(sizeof (qstring));
	b=(qstring *)malloc(sizeof (qstring));
	init(x,a);
	if(a->len<4||a->len>12){
		cout<<"IP wrong format!"<<endl;
		return;
	}
	digui(0,1);
}
int main()
{
	char x[20];
	cout<<"Please enter the IP string."<<endl;
	cin>>x;
	solve(x);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_15742375/article/details/84245350
今日推荐