本文實例解析了C++判斷字符串是否回文的實現過程,通過數據結構中的相關例子,回文判斷中采用過濾空格字符、有效字符依次入棧等方法實現該功能。
具體實例代碼如下:
#include <iostream>using namespace std;#define Max_String_Len 100#include "SqStack.h"http://判斷字符串是否回文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;}
新聞熱點
疑難解答
圖片精選