给定数字串,输出可能的ip地址组合!

it2023-04-17  74

最近看到一个面试问题,决定挺好的,能够考验一个程序员的编程功底,于是自己写了一下。 题目:给定一个数字字符串,要求输出可能的ip地址组合       输入:12342

      输出:1.2.3.42

                  1.2.34.2

                   1.23.4.2

                    12.3.4.2

下面是我写的一个小程序,欢迎拍砖

#include <stdio.h> #include <stdlib.h> #include <string.h> int *stack; int max_top; char *end; void ip_comb(int top, char *tmp) { int next_top = top; int next_value; int i; if(tmp > end || (tmp == end && top != max_top) ){ return; } stack[top] = stack[top] * 10 + *tmp - '0'; if(stack[top] > 255){ return ; } //print result if(top == max_top && tmp == end){ for(i =0; i < max_top; i++){ printf("%d.", stack[i]); } printf("%d\n", stack[max_top]); return; } if(top < max_top){ next_top = top + 1; } next_value = stack[next_top]; ip_comb(next_top, tmp + 1); if(next_value == 0){ stack[next_top] = 0; ip_comb(top, tmp + 1); } return ; } int main(int argc, char ** argv) { char *ip_str; int str_len; int stack_len; //int i; if(argc < 3){ printf("Usage: %s <intstr> <comb_number> \n \t Example: ./test 123421 4 ", argv[0]); } ip_str = strdup(argv[1]); stack_len = atoi(argv[2]); max_top = stack_len -1; str_len = strlen(ip_str); end = ip_str + str_len - 1; stack = (int *)calloc(1, stack_len); //normal case ip_comb(0, ip_str); //We can comb a very long ip str // for(i = 0; i <= str_len - stack_len; i++) // { // stack[0] = 0; // ip_comb(0, ip_str + i); // } return 0; }

 

最新回复(0)