Zerojudge 基礎題庫a022 迴文


回文的定義是:正向,反向讀到的字串均相同。
有了這個天大的提示,腦子裡瞬間跳出:

1.把題目顛倒一下
2.判斷是否相等

例如hi,把它顛倒變成ih
hi != ih,所以不是回文
那theht,把它顛倒變成theht
theht == theht,所以它是回文

有了這個神提示,趕快好好思考吧
那如果還不知道,那就繼續往下看:


(一) 如何儲存字串

你可以這樣:

char a[1000];
cin >> a;

這樣你輸入hello

a[0] a[1] a[2] a[3] a[4] a[5] a[6]   ...
   h     e     l      l      o     \0

當然你也可以學學string,功能強大~

(二) 如何知道字串長度

每個字串最後都是\0,好好利用吧
當然,string 有方便的函數


(三) 如何顛倒字串

答案:第二個提示不是寫無聊的


(四) 我要程式碼!

好吧,只能參考喔,不要複製歐~

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstring>
using namespace std;



int main()
{
    char question[1000];
    while(cin >> question){
        //find \0 (put it in length)
        int length;
        for (int i = 0; i <= 999; i++)
        {
            if (question[i] == '\0')
            {
                length = i;
                break;
            }
        }

        //backward the string and place it in "back"
        char back[length];
        int counter = 0;
        for (int i = 0; i < length; i++)
        {
            if (question[i] != question[length - 1 - i])
            {

                break;
            }
            counter++;
        }
        if (counter == length){
            cout << "yes" << endl;
        }
        else{
            cout << "no" << endl;
        }
    }



}



留言

這個網誌中的熱門文章

Zerojudge 基礎題庫a004 文文的求婚 (Python)

紙蜻蜓的受風面積與紙蜻蜓落地時間的關係 #1 [實驗歷程與Python Matplotlib]

Zerojudge 基礎題庫a013 羅馬數字 (Python)