这篇文章也是在网上找了许多答案但都无法达到100%通过率的情况下写的。
以下是根据前辈的代码改进后实现100%通过率的代码(感谢网上前辈们提供的代码):
#include "dsstring.h" // 请不要删除,否则检查不通过
#include <stdio.h>
#include <stdlib.h>
bool blstr_substr(BLString src, int pos, int len, BLString* sub)
{
if (pos < 0 || pos >= src.len || len < 1)
return false;
Block *p = (sub->head = (Block*)malloc(sizeof(Block))), *q = src.head;
int i = 0, j = 0, k = 0;
p->next = NULL;
while (k <= pos + len - 1 && q && q->ch[i] != BLS_BLANK) {
if (k < pos) {
if (i < BLOCK_SIZE - 1)
i++;
else {
q = q->next;
i = 0;
}
k++;
} else {
p->ch[j] = q->ch[i];
if (i < BLOCK_SIZE - 1)
i++;
else {
q = q->next;
i = 0;
}
if (j < BLOCK_SIZE - 1)
j++;
else {
p->next = (Block*)malloc(sizeof(Block));
p = p->next;
p->next = NULL;
j = 0;
}
k++;
sub->len++;
}
}
if (j) {
sub->tail = p;
while (j < BLOCK_SIZE)
p->ch[j++] = BLS_BLANK;
} else {
for (sub->tail = sub->head; sub->tail->next != p; sub->tail = sub->tail->next)
;
sub->tail->next = NULL;
free(p);
}
return true;
}
这段代码详细展示了如何在C++中实现从BLString对象中提取子串的功能,保证了100%的通过率。通过对已有代码的改进,实现了在不同边界条件下的正确处理,包括处理空格和块大小限制。
1795





