題目:單詞倒排
描述:對字符串中的所有單詞進行倒排。
說明:
1、構成單詞的字符只有26個大寫或小寫英文字母;
2、非構成單詞的字符均視為單詞間隔符;
3、要求倒排后的單詞間隔符以一個空格表示;如果原字符串中相鄰單詞間有多個間隔符時,倒排轉換后也只允許出現一個空格間隔符;
4、每個單詞最長20個字母
數據范圍:字符串長度滿足? 1≤n≤10000;
輸入描述:
輸入一行,表示用來倒排的句子
輸出描述:
輸出句子的倒排結果
示例一:
輸入:I am a student
輸出:student a am I
示例二:
輸入:$bo*y gi!r#l
輸出:l r gi y bo
解題思路:
1,整體思想是雙指針法,定義一對快慢指針 fast,slow;
2,找字母尾部:首先讓 fast 指向數組的尾元素,然后找到從后向前找字母的尾部,當 arr[fast] 不是字母時?fast--,直到指向字母,而后令 slow = fast ,此時 slow 指向字母尾部;
3,找字母頭部:當arr[fast] 是字母時 fast--,直到指向非字母,然后打印 arr[fast+1] 到arr[slow] 之間的值即可,后面加上分隔符;
思路實現:
先輸入字符串因為帶有空格,所以 scanf 不好使,使用 gets ,運用字符串函數 strlen 算出數組實際個數,隨后定義雙指針 fast,slow 并將其賦值;
#include<string.h>
int main() {char arr[10001]={0};gets(arr);int len=strlen(arr);int fast=len-1;int slow=0;
fast=len-1,從后往前開始遍歷數組,并打印;
找字母尾部:首先讓 fast 指向數組的尾元素,然后找到從后向前找字母的尾部,當 arr[fast] 不是字母時?fast--,直到指向字母,而后令 slow = fast ,此時 slow 指向字母尾部;
while(fast>=0 && !isalpha(arr[fast])){fast--;}slow=fast;
找字母頭部:當arr[fast] 是字母時 fast--,直到指向非字母,然后打印 arr[fast+1] 到 arr[slow] 之間的值即可,后面加上分隔符,并且打印;
while(fast>=0 && isalpha(arr[fast])){fast--;}int i=0;for(i=fast+1;i<=slow;i++){printf("%c",arr[i]);}printf(" ");
以上就是這道題的解析,一下是程序源代碼:
#include <stdio.h>
#include<string.h>
int main() {char arr[10001]={0};gets(arr);int len=strlen(arr);int fast=len-1;int slow=0;while(fast>=0){while(fast>=0 && !isalpha(arr[fast])){fast--;}slow=fast;while(fast>=0 && isalpha(arr[fast])){fast--;}int i=0;for(i=fast+1;i<=slow;i++){printf("%c",arr[i]);}printf(" ");}return 0;
}
如有不足之處歡迎來補充交流!
完結。。。
?