Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
Input: S = "loveleetcode", C = 'e'
Output:
Note:
S string length is in [1, 10000].
C is a single character, and guaranteed to be in string S.
All letters in S and C are lowercase.
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int calmin(int a,int b)
{
if(a < b)
return a;
else
return b;
}
int calabs(int a,int b)
{
if(a > b)
return a-b;
else
return b-a;
}
int* shortestToChar(char* S, char C, int* returnSize)
{
int len = strlen(S);
*returnSize = len;
int *res = (int *)malloc(sizeof(int) * len);
/*初始化*/
for(int i = 0; i < len;i++)
{
res[i] = INT_MAX;
}
int pos = -len;
for (int i = 0; i < len; ++i)
{
if (S[i] == C)
pos = i;
res[i] = calmin(res[i], calabs(i,pos));
}
for (int i = len - 1; i >= 0; --i)
{
if (S[i] == C) pos = i;
res[i] = calmin(res[i], calabs(i,pos));
}
return res;
}
在编写这道题目的代码时,对memset函数差点使用错,在C++等实现方式中只需要两个循环就可以解决这个问题,但是C中,如果我对res全1初始化,那么数组中每个元素的值将是-1。这点与C++中的一种用法不同,比如:
vector