【发布时间】:2013-10-26 13:06:03
【问题描述】:
最近我在一次采访中被要求将字符串“aabbbccccdddd”转换为“a2b3c4d5”。目标是用一次出现和重复计数替换每个重复的字符。这里'a'在输入中重复了两次,所以我们必须在输出中将它写为'a2'。我还需要编写一个函数来将格式反转回原来的格式(例如从字符串“a2b3c4d5”到“aabbbccccddddd”)。我可以随意使用 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';
}
我没有发现上述代码有任何问题。还有其他更好的方法吗?
【问题讨论】:
-
请记住,这可能是面试官最喜欢的问题,并且可能已经考虑了几个月。
-
除了奇怪的缩进样式,我觉得没什么不好的。我想我会以几乎相同的方式做到这一点。
-
@H2CO3,抱歉缩进错误,感谢您的回复。
-
@Prabu 不,我不认为交叉发布是个好主意。现在保持原样,这只是您下次考虑提出类似问题时的建议。
-
如果我在面试中问到这个问题,我会对提出先编写反向解决方案的候选人印象深刻。这是因为它更简单(除了知道目标字符串的大小)并且为更困难的压缩提供了一个测试框架。
标签: c++ c visual-c++