题解 | #在字符串中找出连续最长的数字串#
在字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/2c81f88ecd5a4cc395b5308a99afbbec
#include <stdio.h> #include <string.h> typedef struct{ int start; int end; int len; }NUM; void print(char* str, NUM* nums, int numL) { NUM temp; for(int i = 0; i < numL; i++) { nums[i].len = nums[i].end - nums[i].start; } //排序 for(int i = 0; i < numL; i++) { for(int j = i+1; j< numL; j++) { if((nums[i].end - nums[i].start) < (nums[j].end - nums[j].start)) { temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } int maxLen = nums[0].end - nums[0].start; for(int i = 0; i < numL; i++) { if(maxLen == nums[i].len) for(int j = nums[i].start; j < nums[i].end; j++) { printf("%c",str[j]); } } printf(",%d\n",maxLen); } int main() { int i = 0; NUM nums[256] = {0}; char str[256] = {0}; int numcount = 0; int index = 0; int temp = 0; int typeCurrent; char ch = 0; while(EOF != (ch = getchar())) { if('\n' == ch) { if(temp) { nums[i++].end = index; } //print print(str,nums,i); i = 0; temp = 0; index = 0; memset(nums,0x00,sizeof(NUM)*256); memset(str,0x00,256); } else { typeCurrent = (ch >= '0' && ch <= '9'); if(temp != typeCurrent) { if(1 == typeCurrent) { nums[i].start = index; } else if(0 == typeCurrent) { nums[i].end = index; i++; } } temp = typeCurrent; str[index++] = ch; } } return 0; }