ip地址還原(資料結構課本第五章實驗三)
阿新 • • 發佈:2018-11-19
目的:掌握基本遞迴演算法設計
內容:編寫程式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; }