最近、あるインタビューで、文字列 "aabbbccccddddd" を "a2b3c4d5" に変換するように依頼されました。目標は、繰り返される各文字を 1 回の出現と繰り返し回数に置き換えることです。ここで 'a' は入力で 2 回繰り返されるため、出力では 'a2' と記述する必要があります。また、フォーマットを元のフォーマットに戻す関数を作成する必要があります (たとえば、文字列 "a2b3c4d5" から "aabbbccccdddddd" へ)。C または C++ を自由に使用できました。以下のコードを書きましたが、インタビュアーはこれにあまり満足していないようでした。彼は私にこれより賢い方法を試すように頼んだ。
以下のコードではformatstring()
、繰り返し回数を追加するだけで繰り返し文字を削除reverseformatstring()
し、元の文字列に戻すために使用していました。
void formatstring(char* target, const char* source) {
int charRepeatCount = 1;
bool isFirstChar = true;
while (*source != '\0') {
if (isFirstChar) {
// Always add the first character to the target
isFirstChar = false;
*target = *source;
source++; target++;
} else {
// Compare the current char with previous one,
// increment repeat count
if (*source == *(source-1)) {
charRepeatCount++;
source++;
} else {
if (charRepeatCount > 1) {
// Convert repeat count to string, append to the target
char repeatStr[10];
_snprintf(repeatStr, 10, "%i", charRepeatCount);
int repeatCount = strlen(repeatStr);
for (int i = 0; i < repeatCount; i++) {
*target = repeatStr[i];
target++;
}
charRepeatCount = 1; // Reset repeat count
}
*target = *source;
source++; target++;
}
}
}
if (charRepeatCount > 1) {
// Convert repeat count to string, append it to the target
char repeatStr[10];
_snprintf(repeatStr, 10, "%i", charRepeatCount);
int repeatCount = strlen(repeatStr);
for (int i = 0; i < repeatCount; i++) {
*target = repeatStr[i];
target++;
}
}
*target = '\0';
}
void reverseformatstring(char* target, const char* source) {
int charRepeatCount = 0;
bool isFirstChar = true;
while (*source != '\0') {
if (isFirstChar) {
// Always add the first character to the target
isFirstChar = false;
*target = *source;
source++; target++;
} else {
// If current char is alpha, add it to the target
if (isalpha(*source)) {
*target = *source;
target++; source++;
} else {
// Get repeat count of previous character
while (isdigit(*source)) {
int currentDigit = (*source) - '0';
charRepeatCount = (charRepeatCount == 0) ?
currentDigit : (charRepeatCount * 10 + currentDigit);
source++;
}
// Decrement repeat count as we have already written
// the first unique char to the target
charRepeatCount--;
// Repeat the last char for this count
while (charRepeatCount > 0) {
*target = *(target - 1);
target++;
charRepeatCount--;
}
}
}
}
*target = '\0';
}
上記のコードで問題は見つかりませんでした。これを行う他の良い方法はありますか?