給一個字串 s
判斷 s 是不是迴文
指針1 由前往後
指針2 由後往前
如果任意 指針1 位置的字元 != 指針2 位置的字元
則輸入不是回文字串
如果兩指針到中點時字元都相等
則輸入是回文字串
評分結果(參考) : AC (3ms, 344KB)
#include <bits/stdc++.h>
using namespace std;
string isPal(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 << isPal(s);
return 0;
}
反轉輸入的字串
例如 abcdef → fedcba
若反轉後的字串 = 原字串
則輸入是回文字串
(用 <algorithm> - reverse() 實現反轉)
評分結果(參考) : AC (1ms, 348KB)
#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;
}