如何解决这在 C++ 中是什么意思?
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。