本文实例解析了C++判断字符串是否回文的实现过程,通过数据结构中的相关例子,回文判断中采用过滤空格字符、有效字符依次入栈等方法实现该功能。
具体实例代码如下:
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
45
|
#include <iostream>
using namespace std;
#define Max_String_Len 100
#include "SqStack.h"
//判断字符串是否回文
bool ispalindrome( char *in_string)
{
SqStack < char > s(Max_String_Len);
char deblankstring[Max_String_Len], c;
int i = 0;
//过滤空格字符
while (*in_string != '\0' ){
if (*in_string != ' ' )
deblankstring[i++] = *in_string;
in_string++;
}
deblankstring[i] = '\0' ;
//有效字符依次入栈
i = 0;
while (deblankstring[i] != '\0' )
s.Push(deblankstring[i++]);
//从栈中弹出字符依次比较
i = 0;
while (!s.Empty()){
c = s.Top();
s.Pop();
if (c != deblankstring[i])
return false ;
i++;
}
return true ;
}
int main()
{
char instring[Max_String_Len];
cout << "input a string:" << endl;
cin.get(instring, Max_String_Len);
//cout<<instring;
if (ispalindrome(instring))
cout << "\"" << instring << "\"" << " is a palindrome." << endl;
else
cout << "\"" << instring << "\"" << " is not a palindrome." << endl;
system ( "pause" );
return 0;
}
|