a022 - 迴文
題目描述
題目要求判斷輸入的字串是否為迴文。迴文的定義是正向讀取和反向讀取相同的字串。
解題思路
此題使用雙指標法來判斷字串是否為迴文。從字串的兩端開始,比較對應位置的字元。如果字元相同,則將兩個指標向中間移動。如果字元不同,則判斷字串不是迴文。如果迴圈結束時字串的長度小於等於 1,則字串是迴文。
複雜度分析
- 時間複雜度: O(n)
- 空間複雜度: O(1)
程式碼
#include <iostream>
#include <cstring>
using namespace std;
int main(){
string str1;
while(cin >> str1){
for(int i=0;i<str1.size()/2;){
if(str1[0]==str1[str1.size()-1]){
str1.erase(0,1);
str1.erase(str1.size()-1,1);
}else{
break;
}
}
if(str1.size()<=1){
cout << "yes" << endl;
}
if(str1.size()>1){
cout << "no" << endl;
}
}
}