1. 程式人生 > >遞迴實現迴文字串判斷

遞迴實現迴文字串判斷

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;
bool find(const char *str, int n)
{
    if(n<=1) return true;
    else if(str[0]==str[n-1]) return find(str+1, n-2);//去掉首尾兩個,所以n-2
    else return false;
}

int main()
{
    string str[4]= {"abcdeadcba","aba","uestc","aaabbbcccbbbaaa"};
    for(int i=0;i<4;i++)
        {
            cout<<str[i]<<endl;
            if(find(str[i].c_str(), str[i].length()))
                cout<<"Yes\n";
            else
                cout<< "No\n";
        }
}
/*******************************
執行結果如下:
abcdeadcba
No
aba
Yes
uestc
No
aaabbbcccbbbaaa
Yes

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

********************************/

#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;
bool find(const char *str, int n)
{
    if(n<=1) return true;
    else if(str[0]==str[n-1]) return find(str+1, n-2);//去掉首尾兩個,所以n-2
    else return false;
}

int main()
{
    string str[4]= {"abcdeadcba","aba","uestc","aaabbbcccbbbaaa"};
    for(int i=0;i<4;i++)
        {
            cout<<str[i]<<endl;
            if(find(str[i].c_str(), str[i].length()))
                cout<<"Yes\n";
            else
                cout<< "No\n";
        }
}
/*******************************
執行結果如下:
abcdeadcba
No
aba
Yes
uestc
No
aaabbbcccbbbaaa
Yes

Process returned 0 (0x0)   execution time : 0.016 s
Press any key to continue.

********************************/