高中生程式解題系統:迴文 ( Palindrome )

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

題目連結 http://zerojudge.tw/ShowProblem?problemid=a022

演算法:

  • 頭尾的兩個字元進行倆倆判斷
  • 若有不同時,則不是回文。
  • 若相同則往字串中間移動繼續倆倆判斷。


程式碼:

#include <iostream>
using namespace std;
void msg(bool b);
bool isPalindrome( const string &s );
int main()
{
string str;
while(cin >> str)
{
msg(isPalindrome(str));
}
return 0;
}
void msg(bool b)
{
cout << (b?"yes":"no") << endl;
}
bool isPalindrome( const string &s )
{
short len = s.length();
for(short i = 0; i < len / 2; i++)
{
if( s[i] != s[len - 1 - i] )
return false;
}
return true;
}
view raw a022.cpp hosted with ❤ by GitHub

沒有留言: