a022. 迴文 5/16/2025

解法一、雙指針

指針1 由前往後
指針2 由後往前

如果任意 指針1 位置的字元 != 指針2 位置的字元
則輸入不是回文字串

如果兩指針到中點時字元都相等
則輸入是回文字串

✅ 完整代碼

評分結果(參考) : AC

#include <bits/stdc++.h>
using namespace std;
  
string isPalindrome(string& s){
    for(int i=0; i<s.size()/2; i++){
        if(s[i] != s[s.size()-i-1]) return "no";
    }
    return "yes";
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s;
    cin >> s;
    cout << isPalindrome(s);
    
    return 0;
}

解法二、反轉字串

反轉輸入的字串
例如 abcdeffedcba

如果反轉後的字串 = 原字串
代表是回文字串

(用 <algorithm> - reverse() 實現反轉)

✅ 完整代碼

評分結果(參考) : AC

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s1, s2;
    cin >> s1;

    s2 = s1;
    reverse(s2.begin(), s2.end());

    cout << (s1==s2 ? "yes" : "no");
    
    return 0;
}