判斷字符串是不是迴文,使用C++、Python兩種語言

//題目, 判斷一個字符串是不是“迴文”
 
 
#include <iostream>
using namespace std;
 
//! core
bool is_palindrome(char * s){
    int end = strlen(s) - 1;
    int pre = 0;
    while(pre < end){
        if(s[pre] != s[end])
            return false;
        pre ++ ;
        end -- ;
    }
    return true;
}
 
 
int main(){
    char s[] = "abccba";
    bool test, test2;
    test = false;
    test2 = false;
 
    test = is_palindrome(s);
    cout << test << endl;  // 輸出1,則是迴文; 輸出0, 就不是迴文
 
    char s2[] = "12";
    
    test2 = is_palindrome(s2);
    cout << test2 << endl;
 
    return 0;
}

Python版本答案:

#encoding=utf-8
 
#! core
def is_palindrome(s):
    end = len(s) - 1
    i = 0
 
    while(s[i] != s[end]):
        if s[i] != s[end]:
            return False
        i += 1
        end -= 1
 
    return True
 
 
def main():
    b_test1 = False
    b_test2 = False
 
    s1 = "abccba"
    s2 = "12"
 
    b_test1 = is_palindrome(s1)
    # 輸出True,則是迴文; 輸出False, 就不是迴文
    print b_test1
 
    b_test2 = is_palindrome(s2)
    print b_test2
 
main()
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章