【题目概要】
557. Reverse Words in a String III Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string.【思路分析】
单词之间用空格分开,空格ascii码为32,注意是单词之间的顺序不变,单词中的字母顺序相反先分开每一个单词,然后对单词进行处理,该种方法注意末尾的单词如何判断结束,并且也不能添加多余空格返回的字符串,可以malloc堆空间上新建,也可以在原来的字符串中修改,直接返回【代码示例1】
char * reverseWords(char * s){ int len = strlen(s); char *restr = (char*)malloc(sizeof(char)*(len+2)); int reindex = 0; int count = 0; for(int sindex=0; sindex<len; sindex++) { //记录单词的长度 count++; // 判断单词结尾 if(s[sindex] == 32) { int wordtail = sindex-1; count -= 1; while(count && wordtail >= 0) { restr[reindex++] = s[wordtail--]; count--; } // 重新加入空格符号 restr[reindex++] = ' '; } // 判断字符串结束,不能用s[sindex] = '\0'来判断,字符串结束位是访问不到的,越界了 //倒不是以上的原因,而是for循环中最多是len,没有加上结尾符号的长度,因此在里面访问不到 if(sindex == len-1) { int wordtail = sindex; while(count && wordtail >= 0) { restr[reindex++] = s[wordtail--]; count--; } } } restr[reindex] = '\0'; return restr; } 【说明】常见的堆空间的错误,检查malloc的长度是否足够,检查字符串最后一位需要赋值'\0'【代码示例2】
void swap(char *s, int start, int end) { while(start < end) { char temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } char * reverseWords(char * s){ int len = strlen(s); int startindex = 0; for(int i=0; i<len; i++) { if(s[i] == 32) { int endindex = i-1; swap(s, startindex, endindex); startindex = i+1; } } swap(s, startindex, len-1); return s; } 【说明】直接查找空格符来分开单词,确定每一个单词的开始和结束index,建立交换函数,双指针向内交换, 对于最后一个单词,由于结尾没有空格符号,因此单独做一次交换处理