344.反转字符串 https://leetcode.cn/problems/reverse-string/
void reverseString(char* s, int sSize){
int i = 0;
int len = 0;
len = (sSize - 1)/2;
char tmp_c = 0;
for (i = 0; i <= len; i++)
{
tmp_c = s[i];
s[i] = s[sSize - 1 - i];
s[sSize - 1 - i] = tmp_c;
}
return;
}
541. 反转字符串II
https://leetcode.cn/problems/reverse-string-ii/
#ifdef DEBUG
#define debug(fmt, args...) do{printf("[%s+%d] "fmt"\n", __FUNCTION__, __LINE__, ##args);}while(0)
#else
#define debug(fmt, args...)
#endif
char * reverseStr(char * s, int k){
int left = 0;
int right = 0;
int i = 0;
int j = 0;
int len = 0;
char tmp_c = 0;
len = strlen(s);
while((i + 1) * 2 * k <= len)
{
left = i * k * 2;
right = i * k * 2 + k - 1;
debug("left = %d, right = %d", left, right);
for (j = left; j <= (left + right)/2; j++)
{
tmp_c = s[j];
s[j] = s[right - (j - left)];
s[right - (j - left)] = tmp_c;
}
i++;
debug("%s", s);
}
if (len < i * 2 * k + k)
{
left = i * k * 2;
right = len - 1;
debug("left = %d, right = %d", left, right);
}
else if (len >= i * 2 * k + k)
{
left = i * k * 2;
right = i * k * 2 + k - 1;
debug("left = %d, right = %d", left, right);
}
debug("left = %d, right = %d", left, right);
for (j = left; j <= (left + right)/2; j++)
{
debug("j = %d, right - (j - left) = %d", j, right - (j - left));
tmp_c = s[j];
s[j] = s[right - (j - left)];
s[right - (j - left)] = tmp_c;
debug("%s", s);
}
return s;
}
剑指Offer 05.替换空格 https://leetcode.cn/problems/ti-huan-kong-ge-lcof/
char* replaceSpace(char* s){
int i = 0;
int k = 0;
int len = 0;
char *str = NULL;
len = strlen(s);
str = (char *)malloc(3 * len + 1);
if (NULL == str) return NULL;
memset(str, 0, 3 * len + 1);
for (i = 0; i < len; i++)
{
if (' ' == s[i])
{
str[k++] = '%';
str[k++] = '2';
str[k++] = '0';
}
else if (' ' != s[i])
str[k++] = s[i];
}
return str;
}
151.翻转字符串里的单词 https://leetcode.cn/problems/reverse-words-in-a-string/
char * reverseWords(char * s){
int i = 0;
int j = 0;
int len = 0;
char *ptr = NULL;
char *saveptr = NULL;
char **p = NULL;
char *tmp_s = NULL;
debug("come on ^-^");
len = strlen(s);
p = (char **)malloc(sizeof(char *) * len);
if (NULL == p) return NULL;
memset(p, 0, sizeof(char *) * len);
tmp_s = (char *)malloc(sizeof(char) * (len + 2));
if (NULL == tmp_s) return NULL;
memset(tmp_s, 0, sizeof(char) * (len + 2));
debug("tmp_s = %s", tmp_s);
ptr = strtok_r(s, " ", &saveptr);
while(NULL != ptr && 0 != ptr)
{
p[i++] = ptr;
ptr = strtok_r(NULL, " ", &saveptr);
}
debug("come on ^-^");
for (j = i - 1; j >= 0; j--)
{
strcat(tmp_s, p[j]);
strcat(tmp_s, " ");
}
len = strlen(tmp_s);
if (' ' == tmp_s[len - 1]) tmp_s[len - 1] = 0;
strncpy(s, tmp_s, len);
if (NULL != tmp_s) {free(tmp_s); tmp_s = NULL;}
if (NULL != p) {free(p); p = NULL;}
return s;
}
剑指Offer58-II.左旋转字符串