记得最开始学编程的时候逆序字符串都是先malloc一个空间,然后将原字符串反向拷贝过去,但在面试或者笔试的时候不会太这么随意,都会给一些限制。
要求不得另外申请内存,即原地逆序:
int reverse_str(char *str)
{
char *str_tail_p = str;
char *str_head_p = str;
char tmp = 0;
if (str == NULL) {
return -1;
}
while (*str_tail_p) {
str_tail_p++;
}
/*指向最后一个元素*/
str_tail_p -= 1;
while(str_tail_p > str_head_p) {
/*使用了临时变量*/
tmp = *str_head_p;
*str_head_p++ = *str_tail_p;
*str_tail_p-- = tmp;
}
return 0;
}
要求既不能另外申请内存也不能使用临时变量,那就只能依赖于异或了:
int reverse_str(char *str)
{
char *str_tail_p = str;
char *str_head_p = str;
if (str == NULL) {
return -1;
}
while (*str_tail_p) {
str_tail_p++;
}
/*指向最后一个元素*/
str_tail_p -= 1;
while(str_tail_p > str_head_p) {
/*使用异或运算*/
*str_head_p = *str_head_p ^ *str_tail_p;
*str_tail_p = *str_head_p ^ *str_tail_p;
*str_head_p = *str_head_p++ ^ *str_tail_p--;
}
return 0;
}
来个网上经常看到的题,以单词为单位对句子就行逆序,比如:
input:Say hello to the fucking world
output:world fucking the to hello Say
解题思路:
step1 先将每个单词进行逆序,yaS olleh ot eht gnikcuf dlrow
step2 将整个字符串整体逆序,world fucking the to hello Say
/*用始末指针标识单词范围*/
void reverse_word(char *str_head, char *str_tail)
{
char *str_head_p = str_head;
char *str_tail_p = str_tail;
while(str_tail_p > str_head_p) {
*str_head_p = *str_head_p ^ *str_tail_p;
*str_tail_p = *str_head_p ^ *str_tail_p;
*str_head_p = *str_head_p++ ^ *str_tail_p--;
}
}
int reverse_sentence(char *sentence)
{
char *sentence_p = sentence;
char *word_head_p = NULL;
char *word_tail_p = NULL;
if (sentence == NULL) {
return -1;
}
/*找到第一个非空格字符*/
while (*sentence_p) {
if (*sentence_p == ' ') {
sentence_p++;
continue;
}
word_head_p = sentence_p;
break;
}
/*全是空格*/
if (!word_head_p) {
return 0;
}
while (*sentence_p) {
if (*sentence_p == ' ') {
word_tail_p = sentence_p - 1;
/*出现空格且空格前有单词*/
reverse_word(word_head_p, word_tail_p);
word_head_p = sentence_p + 1;
}
sentence_p++;
}
/*找到最后一个字符*/
sentence_p -= 1;
/*当原句为Say hello to the fucking world'\0',即句子不是以空格结尾,
**此时时最后一个单词还没有逆序*/
if (*sentence_p != ' ') {
word_tail_p = sentence_p;
reverse_word(word_head_p, word_tail_p);
}
/*整个句子逆序*/
reverse_word(sentence, sentence_p);
return 0;
}