寻找字符串中遗失的数字并修复
//example:Str="4142434546" Findout missing no 44.Add it to str; //Output:"414243444546". #include <iostream> #include <stdlib.h> bool FixStr(const string& str, string* result) { if (str.empty()) return false; int len = str.length(); int first_len = 1; for (; first_len <= len / 2; ++first_len) { int pos = 0; int num_len = first_len; bool find = false; bool matched = true; int num1 = atoi(str.substr(pos, pos + num_len)).c_str(); pos = pos + num_len; int miss_pos = 0; int miss_num = 0; while (pos < len) { int num2_a = -1; int num2_b = -1; if (pos + num_len > len) { matched = false; break; } else { num2_a = atoi(str.substr(pos + num_len, pos + num_len).c_str()); } if (pos + num_len + 1 <= len) { num2_b = atoi(str.substr(pos + num_len, pos + num_len + 1).c_str()); } if (num1 == num2_a - 1) { num1 = num2_a; pos += num_len; continue; } if (num1 == num2_b - 1) { num1 = num2_b; num_len++; pos += num_len; continue; } if (find) { matched = false; break; } else { if (num1 == num2_a - 2 || num1 == num2_b - 2) { num1 += 2; find = true; miss_pos = pos; miss_num = num1 + 2; if (num1 == num2_b - 2) num_len++; pos += num_len; continue; } matched = false; break; } } if (matched) { if (find) *result = str; else *result = str.substr(0, miss_pos).append(itoa(miss_num)).append(miss_pos, len); return true; } } return false; }
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号