1. 程式人生 > >HDU 1062 Text Reverse

HDU 1062 Text Reverse

題意 pri %d sta include AR mes sin sca

題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1062

題意:轉置一個字符串內的所有單詞。

解法:讀取‘ ’或‘\0’作為一個單詞結束的標記,可用頭文件<string.h>裏的strrev函數轉置單詞,比較方便。也可以采用字符壓棧的方法來轉置單詞(利用堆棧的先進後出性質)。或者用最傳統的方法,數組存放字符,然後轉置。

AC:

//用strrev函數實現,需要註意的是,部分編譯器不支持非標準庫函數strrev。

#include <iostream>
#include <cstring>
using namespace std;
int main() { int n,l,j; cin >> n; getchar(); while(n--) { char p[1010],temp[1010]; gets(p); l = strlen(p),j=0; for(int i = 0 ; i <= l ;i ++) { if(p[i] == || p[i] == \0) { j = 0; strrev(temp);
if(p[i] == ) cout << temp << ; else cout <<temp; temp[0] = \0; } else { temp[j++] = p[i]; temp[j] = \0; } } cout
<<endl; } return 0; }

//用堆棧的方法實現。

#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
 int n;
    char ch;
 scanf("%d",&n);
 getchar(); /*吸收回車符*/
 while(n--)
 {
  stack<char> s; /*定義棧*/
  while(true)
  {
   ch=getchar(); /*壓棧時,一次壓入一個字符*/
            if(ch== ||ch==\n||ch==EOF)
   {
    while(!s.empty())
    {
     printf("%c",s.top()); 
     s.pop(); /*清除棧頂元素*/
    }
    if(ch==\n||ch==EOF)  
     break;  /*絕對不能少,控制輸出結束*/
    printf(" ");
   }
   else
    s.push(ch);
  }
  printf("\n");
 }
 return 0;
}

//用數組的方法實現

#include<stdio.h>
#include<string.h>
int main()
{
    int i,n,len,j,k,t;
    char s1[1005],s2[100];
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        gets(s1);
        len=strlen(s1);
        for(i=0,j=0,t=0;i<len;i++)
        {
            if(s1[i]!= )
                s2[j++]=s1[i]; /*保存單詞*/
            else
            {
                if(t>0) printf(" "); /*控制格式*/
                for(k=j-1;k>=0;k--) 
                    printf("%c",s2[k]); /*反轉輸出*/
                j=0;
                t++;
            }
            if(i==len-1) /*反轉最後一個單詞,這裏要特別註意*/
            {
                printf(" ");
                for(k=j-1;k>=0;k--)
                    printf("%c",s2[k]);
            }
        }
        printf("\n");
    }
    return 0;
}

需要註意:

strlen不計算字符串結尾的‘\0’

用getchar()讀取t後的一個回車,避免編譯器認為回車為第一個字符串.

temp字符串重新定義後加上‘\0‘.

HDU 1062 Text Reverse