LeetCode 758题:“Bold Numbers in String”,请求你找出字符串中全部加粗的数字。加粗的数字是指被星号(*)包抄的数字。比方,在字符串 "ab1*2*3bc"
中,加粗的数字是 1*2*3
。
为懂得决这个成绩,我们可能采取以下步调:
以下是用C言语实现的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* boldNumbersInString(char* s) {
int len = strlen(s);
char* result = (char*)malloc(sizeof(char) * (len + 1));
if (result == NULL) {
return NULL;
}
int j = 0;
int start = -1;
for (int i = 0; i < len; ++i) {
if (s[i] == '*') {
if (start != -1 && (i == len - 1 || !isdigit(s[i + 1]))) {
int numLen = i - start;
for (int k = 0; k < numLen; ++k) {
result[j++] = s[start + k];
}
result[j++] = '*';
start = -1;
}
} else if (isdigit(s[i])) {
if (start == -1) {
start = i;
}
}
}
result[j] = '\0';
return result;
}
int main() {
char s[] = "ab1*2*3bc";
char* result = boldNumbersInString(s);
printf("%s\n", result);
free(result);
return 0;
}
经由过程以上步调跟代码示例,我们可能有效地处理LeetCode 758题。这种方法不只简洁,并且易于懂得,实用于类似的字符串处理成绩。