[英]What does this mean in 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;
}
字符[AZ]
在ASCII 表中的值分別為65-90
, c - 'A'
“標准化”每個[AZ]
到[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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.