解决这个问题的关键在于如何判断一个字符是否对称,以及如何判断一个字符对是否对称。我们可以观察到,题目已经给出了单个对称的字符和一对互相对称的字母。因此,我们可以将这些信息存储在一个哈希表中,其中键是字符,值是它的对称字符。
然后,我们遍历字符串的每一个字符,对于每一个字符,我们查找它的对称字符,然后检查这个对称字符是否和字符串反转后的对应位置的字符相同。如果所有的字符都满足这个条件,那么字符串就是对称的,否则就不是。
C++
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main() {
unordered_map<char, char> my_dic = {{'p', 'q'}, {'q', 'p'}, {'b', 'd'}, {'d', 'b'}};
string temp = "xwmnilouv";
for (char t : temp) {
my_dic[t] = t;
}
int n;
cin >> n;
for (int i = 0; i < n; i++) {
bool f = false;
string s;
cin >> s;
string t = s;
reverse(t.begin(), t.end());
for (int j = 0; j <= s.size() / 2; j++) {
if (my_dic.find(s[j]) == my_dic.end() || my_dic.find(t[j]) == my_dic.end() || s[j] != my_dic[t[j]]) {
cout << "No" << endl;
f = true;
break;
}
}
if (!f) {
cout << "Yes" << endl;
}
}
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Character, Character> map = new HashMap<>();
map.put('p', 'q');
map.put('q', 'p');
map.put('b', 'd');
map.put('d', 'b');
for (char c : "xwmnilouv".toCharArray()) {
map.put(c, c);
}
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < n; i++) {
String s = scanner.nextLine();
String t = new StringBuilder(s).reverse().toString();
boolean flag = true;
for (int j = 0; j <= s.length() / 2; j++) {
if (!map.containsKey(s.charAt(j)) || !map.containsKey(t.charAt(j)) || s.charAt(j) != map.get(t.charAt(j))) {
System.out.println("No");
flag = false;
break;
}
}
if (flag) {
System.out.println("Yes");
}
}
}
}
Python
my_dic = {'p':'q','q':'p','b':'d','d':'b'}
temp = 'xwmnilouv'
for t in temp:
my_dic[t] = t
n = int(input())
for i in range(n):
f = 0
s = list(input())
t = s[::-1]
for j in range(len(s)//2+1):
if s[j] not in my_dic or t[j] not in my_dic or s[j] != my_dic[t[j]]:
print('No')
f = 1
break
if f == 0:
print('Yes')
小红得到了若干个字符串,请你判断字符串是否为对称串。
定义一个字符串为对称串当且仅当该字符串反转后和原串完全相同。例如:poq、owo、bod 是对称的,而 aba 不是对称的。
提示:单个对称的字符有:xwmnilouv,一对互相对称的字母有:p,q、b,d。
第一行一个整数 T(1≤T≤100),表示询问次数。
接下来 T 行每行一个由小写字母组成的字符串,长度小于等于100。
对于每次询问,如果该字符串是对称的,输出 Yes,否则输出 No。
3
bpovoqd
aaaa
poq
Yes
No
Yes