您的位置:首页 > 编程语言 > C语言/C++

如何判斷回文(palindrome) ? (C/C++) (C) (STL)

2010-10-26 19:29 204 查看
Abstract
回文是學習C語言時,常出現的作業與考題。

Introduction
所謂回文,就事字串的第一個字元等於最後一個字元,第二個字元等於倒數第二個字元。

palindrome.c / C

/*
(C) OOMusou 2008 http://oomusou.cnblogs.com
Filename : palindrome.c
Compiler : Visual C++ 9.0 / Visual Studio 2008
Description : Demo how to test palindrome
Release : 10/27/2008 1.0
*/

#include <stdio.h>
#include <string.h>

int is_palindrome(char *s) {
int i, len;

len = strlen(s);

for(i = 0; i < (len /2); i++) {
if (s[i] != s[len-i-1])
return 0;
}

if (i >= len/2)
return 1;
else
return 0;
}

int main() {
char s[256];

while(1) {
gets(s);

if (is_palindrome(s))
printf("%s is palindrome\n", s);
else
printf("%s is not palindrome\n", s);
}
}

18行

for(i = 0; i < (len /2); i++) {
if (s[i] != s[len-i-1])
return 0;
}

依序檢查字串第一個字元是否等於最後一個字元,第二個字元是否等於倒數第二個字元,若發現任何一個字元不同,就不是回文。

感謝沐枫的提醒,在C++有更精簡的寫法。

palindrome.cpp / C++

/*
(C) OOMusou 2008 http://oomusou.cnblogs.com
Filename : palindrome.cpp
Compiler : Visual C++ 9.0 / Visual Studio 2008
Description : Demo how to test palindrome
Release : 10/30/2008 1.0
*/

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int is_palindrome(string s) {
return equal(s.begin(), s.begin() + s.length() /2, s.rbegin());
}

int main() {
string s;

while(1) {
cin >> s;

if (is_palindrome(s))
cout << s << " is palindrome" << endl;
else
cout << s << " is not palindrome" << endl;
}
}

17行

return equal(s.begin(), s.begin() + s.length() /2, s.rbegin());

使用STL的equal()演算法,一行就可以判斷是不是回文了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: