题解 | #单词倒排#
单词倒排
http://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
单词倒排:C语言解法
刚开始没想到用二维数组,用了一个反转字符串的方法
#include<stdio.h>
//反转字符串的方法
void reverse(char *word, int len){
int left = 0, right = len -1;
while(left<right){
char temp = word[left];
word[left++] = word[right];
word[right--] = temp;
}
}
int main(){
char c = 0;
int i = 0, j = 0, size = 0;
char *str = malloc(10000);
char *copy = malloc(10000);
memset(str, 0, 10000);
scanf("%[^\n]",str);//获得带有空格的整个字符串
do{
c = str[i++];
if(c>='a'&&c<='z'||c>='A'&&c<='Z'){
size++;
copy[j++] = c;//遇到合法字符就复制到结果字符串中
}else{
copy[j++] = ' ';//遇到其他非法字符赋值空格
if(copy[j-1] == copy[j-2]){//遇到多个非法字符则使指针后退
j--;
continue;
}
reverse(©[j-size-1], size);//单词反转
size = 0;
}
}while(c != '\0');
reverse(copy, j-1);//整个字符串反转
printf("%s\n",copy);
}