问题描述
chk[c - 'A'] = true;
这在 C++ 中是什么意思? 我试图解决回文重新排序,但我无法理解这一部分。
完整代码如下:
int cnt = 0;
bool chk[26];
string s,ans = "";
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> s;
for (char& c : s) {
if (!chk[c - 'A']) {
chk[c - 'A'] = true;
cnt++;
}
else {
ans += c;
chk[c - 'A'] = false;
cnt--;
}
}
if (cnt >= 2) {
cout << "NO SOLUTION" << endl;
return 0;
}
cout << ans;
for (char c = 'A'; c <= 'Z'; c++) {
if (chk[c - 'A']) {
cout << c;
}
}
reverse(ans.begin(),ans.end());
cout << ans;
return 0;
}
解决方法
字符 [A-Z]
在 ASCII table 中分别具有值 65-90
,c - 'A'
将 [A-Z]
中的每一个“标准化”为 [0,25]
以适应bool chk[]
我假设它的大小为 26 以跟踪字符串中现有的大写字母以重新排序回文。
这样做的更好方法是使用现代 C++ 容器,例如 std::unordered_map
:
#include <unordered_map>
#include <string>
int main() {
std::unordered_map <char,bool> letterExists;
std::string str;
for (auto c : str)
letterExists[c] = true;
}